Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preg Replace html apostrophe

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&#039;s 

(he's)

However when it outputs through this code the words are not normalised and the output is as follows:

he&amp;<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?

like image 295
Matt Ellwood Avatar asked Aug 28 '26 05:08

Matt Ellwood


1 Answers

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);
like image 55
Ja͢ck Avatar answered Aug 29 '26 18:08

Ja͢ck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!