Search code examples
phphtmlregexspecial-characters

How to ignore a word while capturing with a regex?


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'?


Solution

  • 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.