Matt Ellwood
Matt Ellwood

Reputation: 103

Replace words in string beginning with @ symbol

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

Answers (2)

Travesty3
Travesty3

Reputation: 14489

Example

$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

Ja͢ck
Ja͢ck

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

Related Questions