phpregexpreg-replacebackreference

Wrap first word in <b> tag with preg_replace -- can't reference fullstring match


I generated the following regex code with http://gskinner.com/RegExr/ where it works, but when I execute it with PHP, it fails to use the match in the replacement string.

preg_replace(
    '/(?<=\>)\b\w*\b|^\w*\b/',
    '<b>$&</b>',
    'an example'
);

Output:

<b>$&</b> example

Expected:

<b>an</b> example

I know that obviously the $& is not doing the correct thing, but how can I get it to work?


Solution

  • Try with this instead

    preg_replace('/(?<=\>)\b\w*\b|^\w*\b/', '<b>$0</b>', $string);
    

    $0 means it will become the first thing matched in your regex, $1 will become the second etc.

    You could also use back-references; \0 gets the first thing matched back from where you are, \1 gets the second thing matched back etc. More Info