In an example of OS I 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 output was: B > 0
Soon it worked perfectly, but I do not know where I'm going wrong for this other syntax:
[if var == true]
[- success -]
[/if]
Q: The [- success -]
would be echo
, but that's not the case, 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 is in the regular expression, because it does not enter for
, because it does not display anything in the echos inside it. How would you at least find the condition inside [if ]
and work for more than one line? For example:
[if var == true]
[- success -]
<p>Oi, tudo bem?</p>
[/if]