I use this code to make user tags and hashtags work on my small site.
$string = $text;
$pattern = '/(^|\W)(@([a-zA-Z0-9_\-]+))/';
$replacement = '$1<a class="blue" href="/app/profile/$3">$2</a>';
$text = preg_replace($pattern, $replacement, $string);
$string = $text;
$pattern = '/(^|\W)(#([a-zA-Z0-9_\-]+))/';
$replacement = '$1<a class="blue" href="/app/find/search/$3">$2</a>';
$text = preg_replace($pattern, $replacement, $string);
echo $text;
My database saves all pieces of text like this:
he's
(he's)
However when it outputs through this code the words are not normalised and the output is as follows:
he&<a class="blue" href="/app/find/search/039">#039</a>;s
When it shold just be "he's" How can I get the preg replace to see it as an apostrophe?
You can use a look-behind assertion:
/(?<=^|\s)(#|@)(\w+)/
Preceded by either the beginning of a string or a space (including tabs, newlines, etc.), a hash or at symbol followed by at least one "word like" character.
So:
$string = preg_replace_callback('/(?<=^|\s)(#|@)(\w+)/', function($match) {
switch ($match[1]) {
case '#':
$format = '<a class="blue href="/app/find/search/%s">%s</a>';
break;
case '@':
$format = '<a class="blue href="/app/profile/%s">%s</a>';
break;
default:
return $match[0];
}
return sprintf($format, urlencode($match[2]), $match[1] . $match[2]);
}, $string);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With