Mihai Vilcu
Mihai Vilcu

Reputation: 1967

php template nested loop

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

Upvotes: 0

Views: 184

Answers (1)

Qtax
Qtax

Reputation: 33918

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

Upvotes: 1

Related Questions