0

I'm playing around trying to make a small template class and i run into a little trouble
I'm trying to match this nested loop

<ul>
    {each $nestedArr}
        <li>{$group}</li>

        <ul>
            {each $users}
                <li>{$name}</li>
            {/each}
        </ul>

    {/each}
</ul>

What i got so far is this

preg_match('/{each \$nestedArr}(?:(?R)|(.*?)){\/each}/is', $this->buffer, $match);

But the problem is that it stops at the first closing {/each}
Any tips on how i can fix that ?

For conviniance i also added on regex101

4
  • Just out of curiosity, why are you trying to do this? Why not use Symfony or something? Commented Aug 3, 2013 at 21:55
  • 1
    @putvande: Symfony is a full framework or a number if differnt components. I think you mean the Twig component. That said I agree... Unless this is purely for learning experience you're better off using Twig or Smarty, and then adding any functionality you need that isnt present by extending. Commented Aug 3, 2013 at 22:01
  • it is indeed just for practice, but even so it's interesting to know how it works Commented Aug 3, 2013 at 22:15
  • Practice is good. I think you would be better off not using regular expressions, however. The templating language looks very simple and could easily be parsed using simple string functions (strpos for finding matching {} braces, for example) and recursive function calls for processing text between each blocks. Regular expressions are powerful, but for solving simple problems you usually only need simple solutions. Commented Aug 4, 2013 at 9:09

1 Answer 1

1

If you are interested in how you can use regex to do this read on, but as noted in the comments you are better off using some well tested component for this in production (which probably uses a better way to parse the code).

To match nested {each $...} tags you could use this:

/{each\ \$\w+}  (?: [^{] | {(?!\/?each) | (?R) )*  {\/each}/x

But that doesn't match a specific tag like you seem to want.

To do that you could use:

/(?={each\ \$nestedArr}) ({each\ \$\w+}  (?: [^{] | {(?!\/?each) | (?1) )*  {\/each})/x
Sign up to request clarification or add additional context in comments.

2 Comments

It still seems to go till the first {/each}, do i need to watch out for anything else ?
@ionutvmi, oops, added a } for some reason after i tested. Fixed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.