简体   繁体   中英

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM