I'm trying to nest tags with regex. It's a "for" loop. This is the code I have so far: <?php $test = "{for:a in b} For1 {for:c in d} For2 {/for} {for:e in f} Nothing {/for} {/for}"; $pattern = '#\{for:(.*)\sin\s(.*)}((?:[^{]|\{(?!/?for})|(?R))+)\{/for}#ms'; preg_match_all($pattern, $test, $matches); print_r($matches); ?> PHP: The problem is that when I add any attributes to the "for" tag, the regex stops working. So I have {for:a in b} right now, but, if I remove everything so it reads just {for}, it will work. For example, this works: This code is WORKING: <?php $test = "{for} For1 {for} For2 {/for} {for} Nothing {/for} {/for}"; $pattern = '#\{for}((?:[^{]|\{(?!/?for})|(?R))+)\{/for}#'; preg_match_all($pattern, $test, $matches); print_r($matches); ?> PHP: Can anyone help? It would be best if you can provide an explanation to why your fix works and mine doesn't, but it's not necessary, I just need the code/fix. Thanks.