I donβt know if there is a regular expression that receives all internal and external tags in one call, but you can use this regular expression /\{(([^\{\}]+)|(?R))*\}/ from a question related to you and iterate over the results recursively.
I added your tag name and some sub-elements in regexp for clarity:
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; }
Returns an array with all matches containing the entire match, the tag name, the contents of the brackets, and an iteration counter, showing how often the match was nested inside other tags. I added one more level of nesting of your line for demonstration:
$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>';
The output will be:
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 ) )
Dervo source share