3
In an example of the OS found:
<?php
$a = 22;
$b = 33;
$template = '
[if $b>0 ]
B > 0
[/if]';
// IF - ENDIF
preg_match_all('/\[if(.*?)\][\s]*?(.*)[\s]*?\[\/if\]/i', $template, $regs, PREG_PATTERN_ORDER);
for ($i = 0; $i < count($regs[0]); $i++) {
$condition = $regs[1][$i];
$trueval = $regs[2][$i];
$res = eval('return ('.$condition.');');
if ($res===true) {
$template = str_replace($regs[0][$i],$trueval,$template);
} else {
$template = str_replace($regs[0][$i],'',$template);
}
}
echo '<h3>Template</h3><pre>'.htmlentities($template).'</pre>';
The exit was: B > 0
Soon it worked perfectly, but I don’t know where I’m going with this other syntax:
[if var == true]
[- success -]
[/if]
P.S: The [- success -]
would be a echo
, but that’s beside the point, I’m trying with the following code:
private function _if()
{
// IF - ENDIF
preg_match_all('/\[if(.*?)\]*?(.*)*?\[\/if\]/', $template, $regs, PREG_PATTERN_ORDER);
for ($i = 0; $i < count($regs[0]); $i++) {
$condition = $regs[1][$i];
$trueval = $regs[2][$i];
echo "Condition: {$condition}<br>";
echo "TrueVal: {$trueval}<br>";
/*
$res = eval('return ('.$condition.');');
if ($res===true) {
$template = str_replace($regs[0][$i],$trueval,$template);
} else {
$template = str_replace($regs[0][$i],'',$template);
}*/
}
}
I think the error lies in the regular expression, because it doesn’t even enter the for
, because it neither exhibits anything in the Segments within it. How would you at least find the condition within the [if ]
and work for more than one line? For example:
[if var == true]
[- success -]
<p>Oi, tudo bem?</p>
[/if]
It worked perfectly, now I’m getting it!
– Leonardo