Reputation: 103
I need to replace the words that contain an @
symbol with a link in php
e.g.:
$string = "you would love this @matt";
would turn into "you would love this <a href="/user/matt">@matt</a>
"
From research I need to use preg_replace()
, but don't know where to start. Any ideas?
Thanks
Upvotes: 0
Views: 108
Reputation: 14489
$string = "you would love this @matt";
$pattern = '/(^|\W)(@([a-zA-Z]+))/';
$replacement = '$1<a href="/user/$3">$2</a>';
echo preg_replace($pattern, $replacement, $string);
Upvotes: 2
Reputation: 173662
You can use preg_replace_callback()
for that:
echo preg_replace_callback('/(?<=\s)@(\w+)/', function($match) {
return sprintf('<a href="/user/%s">@%s</a>',
urlencode($match[1]),
$match[1]
);
}, htmlspecialchars($string));
Doing this enables you to do apply additional formatting for each match.
Upvotes: 2