Reputation: 541
I am having a problem with the following code:
$input = '#2weeksago #1year&2weeksold #keyword';
$output = preg_replace('/(?:.^|\s)#(\w+)/', ' <span class="hashtag">#$1</span>', $input);
print($output);
I want each word within a hashtag surrounded with a span-attribute. This works for the most keywords, but hashtags with a symbol in it doesn't work.
Output
<span class="hashtag">#2weeksago</span> <span class="hashtag">#1year</span>&2weeksold <span class="hashtag">#keyword</span>
Can someone help expand this preg_replace?
Upvotes: 0
Views: 30
Reputation: 42984
If you don't want to break at "word boundaries" but continue with matching till the next white space character, then you need to do exactly that:
<?php
$input = '#2weeksago #1year&2weeksold #keyword';
$output = preg_replace('/(?:.^|\s|^)#([^\s]+)/', ' <span class="hashtag">#$1</span>', $input);
print($output);
The output obviously is:
<span class="hashtag">#2weeksago</span> <span class="hashtag">#1year&2weeksold</span> <span class="hashtag">#keyword</span>
Upvotes: 1