Identify if and endif with regex?

3

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]
    
asked by anonymous 20.09.2016 / 00:30

1 answer

4

In the test I performed REGEX worked perfectly.

However I think it would be better to replace it with ~\[if([^\]]*)\]\s*?(.*?)\[\/if\]~s

See working at REGEX 101 .

The big move is in the modified s that causes . (Dot) to accept line breaks \n .

Then you will find the condition in group 1 and "trueval" (content) in group 2.

Note

  • It may be interesting to switch ([^\]]*) to ( [^\]]+) to ensure that you have at least one condition in if .
  • (.*?) ensures that you will get as little content as possible.
20.09.2016 / 07:12