Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP replace string using overlapping regular expressions

How to replace string using overlapping regular expressions?

Hello! Im trying to add html tags into string. Im using function preg_replace(), but when my patterns in array are overlaped the preg_replace doesn't work.

$string = 'abc';
$patterns[0] = '/a/';
$patterns[1] = '/abc/';
$replacements[0] = '<b>$0</b>';
$replacements[1] = '<i>$0</i>';
echo preg_replace($patterns, $replacements, $string);

This produce the following output:

<b>a</b>bc

But i expected this output:

<b><i>a</b>bc</i>

It seems like preg_replace takes first pattern and replace it with first replacement and then search for second pattern but it search in modified string. I must use functions which support regular expressions.

like image 813
martaus Avatar asked Dec 08 '25 14:12

martaus


1 Answers

It's because they don't run simultaneously, but in loop. And after first expression you end up with <b>a</b>bc so there is no more any abc for second expression to match.

It's simply as that. And that's good, because thanks to that you won't end with invalid markup. You will. Regex is serious problem with HTML or XML.

Use some DOM interpreter and library, like PHP's DOMDocument

like image 141
Forien Avatar answered Dec 11 '25 05:12

Forien



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!