Skip to content
Advertisement

Wrap first word in 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(
    '/(?<=>)bw*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?

Advertisement

Answer

Try with this instead

preg_replace('/(?<=>)bw*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; gets the first thing matched back from where you are, 1 gets the second thing matched back etc. More Info

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement