我不知道,如果有一个正则表达式,得到您所有的内,外标签一个电话,但你可以使用这个正则表达式/\{(([^\{\}]+)|(?R))*\}/
从你链接的问题,递归迭代到结果。
我加了你的变量名和一些指定的子模式的正则表达式更加清晰:
function search_tags($string, $recursion = 0) {
$Results = array();
if (preg_match_all("/(?<tagname>[\w]+)\{(?<content>(([^\{\}]+)|(?R))*)\}/", $string, $matches, PREG_SET_ORDER)) {
foreach ($matches as $match) {
$Results[] = array('match' => $match[0], 'tagname' => $match['tagname'], 'content' => $match['content'], 'deepness' => $recursion);
if ($InnerResults = search_tags($match['content'], $recursion+1)) {
$Results = array_merge($Results, $InnerResults);
}
}
return $Results;
}
return false;
}
此方法返回包含整个匹配,标签名,括号的内容和所有匹配的数组一个迭代计数器,显示您匹配的频率嵌套在其他标签内的频率。我已经加入到另一个嵌套级别的字符串示范:
$text = "This is some random text, tag1{while this is inside a tag2{tag}}. This is some other text tag3{also with a tag tag4{and another nested tag5{inside}} of it}.";
echo '<pre>'.print_r(search_tags($text), true).'</pre>';
输出将是:
Array
(
[0] => Array
(
[match] => tag1{while this is inside a tag2{tag}}
[tagname] => tag1
[content] => while this is inside a tag2{tag}
[deepness] => 0
)
[1] => Array
(
[match] => tag2{tag}
[tagname] => tag2
[content] => tag
[deepness] => 1
)
[2] => Array
(
[match] => tag3{also with a tag tag4{and another nested tag5{inside}} of it}
[tagname] => tag3
[content] => also with a tag tag4{and another nested tag5{inside}} of it
[deepness] => 0
)
[3] => Array
(
[match] => tag4{and another nested tag5{inside}}
[tagname] => tag4
[content] => and another nested tag5{inside}
[deepness] => 1
)
[4] => Array
(
[match] => tag5{inside}
[tagname] => tag5
[content] => inside
[deepness] => 2
)
)
+1递归子模式。 – cmbuckley 2012-02-03 13:16:15
@cbuckley,这两个原始表达式的工作。第一个原始的更短,更好,但在捕获中包含周围的“{}”。 – Qtax 2012-02-05 03:28:42
同意;我只是使正则表达式和示例一致。随意恢复我的更改,或编辑提及这两个正则表达式。 – cmbuckley 2012-02-06 00:20:23