Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

wrap <b>-tag around first word of string with preg_replace

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?

like image 667
John Doe Smith Avatar asked Dec 13 '22 01:12

John Doe Smith


1 Answers

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

like image 154
Timm Avatar answered Dec 28 '22 06:12

Timm