I have this string:
$text = "What's your #name ?"
And I have this code capturing 'name' and '039':
preg_replace("/\B#(\w+)/", "<a href='url'>#$1</a>", $text);
Any idea about how to capture 'name' but not '039'?
Use a negative lookbehind:
echo preg_replace("/(?<!\S)#(\w+)/", "<a href='url'>#$1</a>", $text);
Regex autopsy:
(?<!\S)
- A negative lookbehind - to assert that the #
is not preceded by a non-whitespace character#
- matches the #
character literally(\w+)
- first capturing group