It is necessary to optimize the speed of the regular expression, which should look in the text below from the position found back and find the previous matching tag. At the same time between the tags {if $var} , {else} , {/if} can be any characters. Tags can be repetitive. You need to push off from the first closing tag {/if} . PHP programming language.

 {if $var1} {if $var2} {if $var3} любой текст {else} text *(&@$@!/\#<?>~`.,+-_ {/if} {/if} {if $var4} any symbols {elseif $var5} text {else} {if $var6}{/if} {/if} {if $var7}{/if} {else} text and symbols *(&@$$@! {/if} 

In this example, the previous tag will be {if $var3}

To search {if $var} used:

 echo preg_replace('/(?(?=\/.?)|({if \$var3}).*?)*(?={\/if})/msi', $replacement, $string); 

Link to example regex101.com

  • What programming language do you write and is it necessary to use regulars? - VenZell
  • @ Konstantin Pavlovich, make out the answer with the answer, but not editing the question. - Visman 5:56 pm
  • one
    Or maybe just like that '~({[^}]*})\s*[^{}]*\s*{/if}~' ? - Wiktor Stribiżew
  • (({if \$var})[^}]*})\s*[^{}]*\s*{/if} - if you search at the beginning of the text, then the steps are less, but in the middle of the text it gives 2450 steps in comparison with (?(?=\/.?)|({if \$var}).*?)*(?={\/if}) which yielded 1531 steps [link to the comparison example] ( regex101.com / r / aY1yI4 / 3 ) - Konstantin Pavlovich
  • It is not necessary to implement such things through regular expressions. Instead, you should go through the template once and build an AST for it, with which you will have to work further. This is much more efficient and more flexible than any regular-trick you can do. - Dmitriy Simushev

1 answer 1

 preg_match('/{if(?(?={\/?if)|.)*(?={\/if})/', $txt, $matches); var_dump($matches); // Результат [0]=> string(10) "{if $var3}" 

The construction (?(?={\/?if)|.) Translates as finding any characters, only that they would not be {if} or {/if} .

Regex101.com example

  • I just can not understand, why use print var_dump() ? Without print , everything works ... - VenZell
  • @VenZell with barley similar function confused. corrected - Mike
  • @ReinRaus And the answer was written to another question, where the recursion was not needed because searched for the deepest tag. TC dramatically changed the text of the question after the written answer, using the elements of my answer in the new text. - Mike
  • Yes, I'm sorry, there is a lot of additional information in the question contained in the comments, so I didn’t take it correctly at first. - ReinRaus