使用正则表达式捕获时如何忽略单词?

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

Regex101 demo.

You could use [A-Za-z]+ instead of \w+.