Before all, sorry for my pretty bad english.
I'm trying to make a PHP template engine using regex & preg_match_all.
My regex looks like :
/\{:[\s]*?[\n]*?[\s]*?if(.*?):\}[\s]*?(.*?)[\s]*?(\{:[\s]?else[\s]?:\}[\s]*?(.*?)[\s]*?)\{:[\s]*?endif[\s]*?:\}/is
My PHP looks like :
preg_match_all('/\{:[\s]*?[\n]*?[\s]*?if(.*?):\}[\s]*?(.*?)[\s]*?(\{:[\s]?else[\s]?:\}[\s]*?(.*?)[\s]*?)\{:[\s]*?endif[\s]*?:\}/is', $template, $regs, PREG_PATTERN_ORDER);
for ($i = 0, $iMax = count($regs[0]); $i < $iMax; $i++) {
$condition = $regs[1][$i];
$trueval = $regs[2][$i];
$falseval = $regs[4][$i] ?? false;
$res = eval('return ('.$condition.');');
if ($res===true) {
$template = str_replace($regs[0][$i],$trueval,$template);
} else {
$template = str_replace($regs[0][$i],$falseval,$template);
}
}
When in my template string I got only one if, something like this :
{: if $var > 3 :}
The variable $var is > than 3
{: else :}
The variable $var is < than 3
{: endif :}
It will work perfectly. But if in this if I put an other if, it will not work.
{: if $var > 3 :}
The variable $var is > than 3
{: if $var1 < 2 :}
The variable $var1 < than 2
{: else :}
The variable $var1 > than 2
{: endif :}
{: else :}
The variable $var is < than 3
{: endif :}
In this case, the preg match all will not work properly, and will output me this :
{: if $var > 3 :}
The variable $var is > than 3
{: if $var1 < 2 :}
The variable $var1 is < than 2
{: else :}
The variable $var1 is > than 2
{: endif :}
It will stop at the first endif, not the good one. I have absolutely no idea on how to do this. If someone have an idea ? Thank you so much for your time and your help !