、であなたのすべての内側と外側のタグを取得する正規表現がある場合1つの呼び出しですが、リンクした質問のこの正規表現/\{(([^\{\}]+)|(?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
@cbuckley、どちらも元の表現が動作します。最初のオリジナルのものは、より短く、より良いですが、キャプチャでは '{}'を取り囲んでいます。 – Qtax
合意。私はちょうど正規表現とその一貫した例を作っていた。私の変更を元に戻すか、両方の正規表現に言及するように編集してください。 – cmbuckley