$re = '/{\s*{\s*#\s*(?<operator>endcase|endswitch|endfor|endif|if|elif|else|for|switch|case|default)\s*(?<args>[^}]*)\s*}\s*}\s*(?<body>[^{]*(?:\s*{\s*{\s*#\s*(?!(?&operator))\s*[^}]*\s*}\s*}\s*[^{]*)*)/ui';
$str = '<div>
{{#if arg1.arg2}}
<span>{{#var arg3 static}}</span>
blablabla{{#for k, v in arg4}}
<p>{{#var k}}<span>{{#var v.arg5}}</span></p>
{{#if (k == "test" or v != 0) and k == 0}}
<span></span>
{{#elif k == 0}}
<p></p>
{{#else}}
<div></div>
{{#endif}}
{{#endfor}}
{{#endif}}
{{#switch arg6}}
{{#case 5}}
case 5
{{#case 6, 7, 8}}
case 6, 7, 8
{{#endcase}}
{{#default}}
def
{{#endcase}}
{{#endswitch}}
{{#for i as 0, 5}}
test i
{{#endfor}}';
preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
// Print the entire match result
var_dump($matches);
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for PHP, please visit: http://php.net/manual/en/ref.pcre.php