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.
JavaScript
x
preg_replace(
'/(?<=>)bw*b|^w*b/',
'<b>$&</b>',
'an example'
);
Output:
JavaScript
<b>$&</b> example
Expected:
JavaScript
<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
JavaScript
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