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);
'~({[^}]*})\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