I recommend using a lookbehind before matching the @
then one or more characters which are not a space or @
.
The "one or more" quantifier (+
) prevents the matching of mentions that mention no one.
Using a lookbehind is a good idea because it not only prevents the matching of email addresses and other such unwanted substrings, it asks the regex engine to primarily search @
s then check the preceding character. This should improve pattern performance since the number of spaces should consistently outnumber the number of mentions in comments.
If the input text is multiline or may contain newlines, then adding an m
pattern modifier will tell ^
to match all line starts. If newlines and tabs are possible, is will be more reliable to use (?<=^|\s)@([^@\s]+)
.
Code: (Demo)
$comment = "@name kdfjd @@ fkjd as@name @ lkjlkj @name";
var_export(
preg_replace(
'/(?<=^| )@([^@ ]+)/',
'<a href="/$1">$0</a>',
$comment
)
);
Output: (single-quotes are from var_export()
)
'<a href="/name">@name</a> kdfjd @@ fkjd as@name @ lkjlkj <a href="/name">@name</a>'
\s
– Landel