如何使用php进入嵌套的花括号?
示例:
{{ text1 {{text2 text3 {{text4}} text5}} }}应该输出
1- text1 {{text2 text3 {{text4}} text5}}
2- text2 text3 {{text4}} text5
3- text4发布于 2012-07-07 15:32:00
我已经找到了我正在寻找的答案,并把它放在这里,这样每个人都可以使用它。它确实很简单,只有一行:
$text1=preg_replace("/\{\{(([^{}]*|(?R))*)\}\}/",'',$text1);它将搜索所有{{text}}并将其替换为您想要的任何内容。您还可以使用preg_match_all将它们全部放入一个数组中。
发布于 2012-07-02 20:59:28
这需要跟踪括号的数量,而不能使用正则表达式来完成。为此,您必须创建自己的解析器逻辑。Regex is not a parser,对不起。
Here is another similar question with the same response as mine
And here is a SO about building parses (in Java, but it should translate well enough)
发布于 2012-07-02 22:35:02
像Perl一样,PCRE可以匹配任意深度的嵌套结构(仅限于内存-见下文)。下面是一个经过测试的脚本:
匹配嵌套括号的正则表达式
<?php // test.php Rev:20120702_1100
$re_nested_double_bracket ='% # Rev:20120702_1100
# Match {{...{{...}}...}} structure with arbitrary nesting.
\{\{ # Opening literal double bracket.
( # $1: Contents of double brackets.
(?: # Group for contents alternatives.
[^{}]++ # Either one or more non-brackets,
| (?R) # or a nested bracket pair,
| \{ # or the start of opening bracket
(?!\{) # (if not a complete open bracket),
| \} # or the start of closing bracket.
(?!\}) # (if not a complete close bracket).
)* # Zero or more contents alternatives.
) # End $1: Contents of double brackets.
\}\} # Closing literal double bracket.
%x';
$results = array(); // Global array to receive results.
// Recursively called callback routine adds to $results array.
function _bracket_contents_callback($matches) {
global $results, $re_nested_double_bracket;
$results[] = $matches[1];
preg_replace_callback($re_nested_double_bracket,
'_bracket_contents_callback', $matches[1]);
return $matches[0]; // Don't modify string.
}
$input = file_get_contents('testdata.txt');
preg_replace_callback($re_nested_double_bracket,
'_bracket_contents_callback', $input);
$count = count($results);
printf("There were %d matches found.\n", $count);
for ($i = 0; $i < $count; ++$i) {
printf(" Match[%d]: %s\n", $i + 1, $results[$i]);
}
?>当对原始post中的测试数据运行时,正则表达式匹配如下:
输出示例:
There were 3 matches found.
Match[1]: text1 {{text2 text3 {{text4}} text5}}
Match[2]: text2 text3 {{text4}} text5
Match[3]: text4
请注意,此正则表达式匹配最外面的一组可能嵌套的括号,并将括号之间的内容捕获到组$1中。该脚本使用preg_replace_callback()函数递归地匹配嵌套括号内容并将其添加到结果数组中。
“任意深度”请注意,此解决方案可以匹配任意“任意深度”的嵌套括号,但始终受到系统内存、可执行堆栈大小以及pcre.backtrack_limit、pcre.recursion_limit和memory_limit配置变量的限制。请注意,对于给定的主机系统,如果主题字符串太大和/或嵌套太深,则此正则表达式解决方案肯定会失败。PHP/PCRE库甚至有可能导致正在运行的可执行文件产生堆栈溢出、分段错误和程序崩溃!请参阅我对一个相关问题的回答,以深入讨论这种情况是如何发生的以及为什么会发生(以及如何避免这种情况并优雅地处理这种错误):RegExp in preg_match function returning browser error和PHP regex: is there anything wrong with this code?。
注意:这个问题(和我的答案)几乎与:Parsing proprietary tag syntax with regex - how to detect nested tags?相同,但在这个答案中,提供了一个更完整的解决方案,它递归地匹配并存储所有嵌套的括号内容。
https://stackoverflow.com/questions/11294144
复制相似问题