mardi 20 mars 2018

How to parse the most nested IF statement via Regex in PHP

I work with @if|@else|@endif statement in my HTML code and I need find most nested statement/condition (a condition that don't contain another condition) via preg_replace_callback() function.

When function resolve the condition on last level, it start again with parent IF statement as long as all conditions/IF statements will be solved.

In every iteration I need find the actual most nested conditions.

This is example of my HTML code:

  @if($i%2 == 0)

     <something html> 

        @if($i==2)

           <something html>

           @if($i == 0)

              <something html>

           @endif

        @endif

     <something html>

  @else 

     <something html>

        @if($i==2)

           <something html>

        @endif

     <something html>

  @endif

I try something like:

$pattern = '/@if\s*\(\s*(.*)\s*\)\s*((?!@if|@endif).*)\s*(?:@else\s*((?!@if|@endif).*))?\s*@endif/s';

Thank you in advance for your help.

Aucun commentaire:

Enregistrer un commentaire