Php regex, trying to exclude a match within another match

72 Views Asked by At

I have this regex to scan for each loops in my views, it almost does what I want, but not entirely. Im using this regex atm:

(?=({{each\s+([^{}]*)}}((?>(?!{{#?each).|(?1))*){{#each}}))

When I have an each-loop within another each-loop, it shows the matches correctly, but I don't want to inner each loop to be a match. I am planning to process this 2nd match recursively. Here is an example HTML:

<div class="rows-container">
{{each infoItems}}
    <div class="row">
        <div class="row-key"></div>
    </div>

    <div class="sub-container">
    {{each subItems}}
        <div class="row">
            <div class="row-key"></div>
        </div>
    {{#each}}
    </div>
{{#each}}
</div>

<div class="rows-container">
{{each newsItems}}
    <div class="row">
        <div class="row-key"></div>
    </div>
{{#each}}
</div>

Will produce the following results:

//MATCH 1:
1. {{each infoItems}} <div class="row"> <div class="row-key"></div> </div> <div class="sub-container"> {{each subItems}} <div class="row flex-wrap"> <div class="row-key"></div> </div> {{#each}} </div> {{#each}}
2. infoItems
3. <div class="row"> <div class="row-key"></div> </div> <div class="sub-container"> {{each subItems}} <div class="row flex-wrap"> <div class="row-key"></div> </div> {{#each}} </div> 


//MATCH 2:
//This is the match I was trying to exclude:
4. {{each subItems}} <div class="row flex-wrap"> <div class="row-key"></div> </div> {{#each}}
5. subItems
6. <div class="row flex-wrap"> <div class="row-key"></div> </div> 

//MATCH 3:
7. {{each newsItems}} <div class="row"> <div class="row-key"></div> </div> {{#each}}
8. newsItems
9. <div class="row"> <div class="row-key"></div> </div> 

As you can see all I need is: the full result (which is useful for the replace callback), the array name, & the content. I have tried puzzling with the regex,

{{each\s+([^{}]*)}}((?>(?!{{#?each).|(?1))*){{#each}}

This will only give the 2nd & the third, but not the first ='( I'm starting to think I'm in over my head with regexes this complex, losing the understanding of them... but I like to push things.

Is there a way to capture the 1st and 3rd match? with allowing other each loops inside (only 1 inside required.. for now), but not matching them. A little bit of explanation or feedback will be very much appreciated, but I got some time on my hands and I am in for a puzzle.

0

There are 0 best solutions below