[英]PHP replace string using overlapping regular expressions
Hello! 你好! Im trying to add html tags into string.
我试图将html标签添加到字符串中。 Im using function preg_replace(), but when my patterns in array are overlaped the preg_replace doesn't work.
我使用函数preg_replace(),但当我的数组中的模式重叠时,preg_replace不起作用。
$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. 似乎preg_replace采用第一个模式并用第一个替换替换它,然后搜索第二个模式,但它搜索修改后的字符串。 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. 在第一次表达之后,你最终会得到
<b>a</b>bc
因此第二个表达式不再有任何abc
匹配。
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.
正则表达式是HTML或XML的严重问题。
Use some DOM interpreter and library, like PHP's DOMDocument
使用一些DOM解释器和库,比如PHP的
DOMDocument
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.