PHP,preg_replace 中的嵌套模板 [英] PHP, nested templates in preg_replace
问题描述
preg_replace("/\[b\](.*)\[\/b\]/Usi", "<strong>$1</strong>", "Some text here... [b][b]Hello, [b]PHP![/b][/b][/b] ... [b]and here[/b]");
返回
Some text here... <strong>[b]Hello, [b]PHP!</strong>[/b][/b] ... <strong>and here</strong>
但我需要替换所有 [b]...[/b] 标签.为什么我的情况不会发生这种情况?
But i need to replace all [b]...[/b] tags. Why this doesn't happen in my case?
推荐答案
它不起作用的原因:你抓住第一个 [b],然后继续下一个 [/b],中间的任何东西都保持不变.即,您更改了外部的 [b] 标签,但不更改嵌套在其中的标签.
The reason it doesn't work: You catch the first [b], then move on to the next [/b], and leave anything in between unchanged. Ie, you change the outer [b] tags, but not the ones nested inside.
您对@meza 的评论表明您想成对替换伪标签,否则就不要动它们.最好的方法是使用多遍,就像这样
Your comment to @meza suggests you want to replace the pseudo tags in pairs, or else leave them untouched. The best way to do this is to use multiple passes, like this
$markup = "Some text here... [b][b]Hello, [b]PHP![/b][/b][/b] ... [b]and here[/b]";
$count = 0;
do {
$markup = preg_replace("/\[b\](.*?)\[\/b\]/usi", "<strong>$1</strong>", $markup, -1, $count );
} while ( $count > 0 );
print $markup;
我什至不确定您是否可以在单行正则表达式中做到这一点,但即使可以,它也会相当复杂,因此难以维护.
I'm not even sure if you can do it in a one-line regex, but even if you could, it would be rather complex and therefore hard to maintain.
这篇关于PHP,preg_replace 中的嵌套模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!