Identify if and endif with regex?

Asked

Viewed 101 times

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]

1 answer

4


In the test I performed the REGEX worked perfectly

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

See working in REGEX 101.

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

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

Note

  • perhaps it is interesting to exchange ([^\]]*) for ( [^\]]+) to ensure that you have at least one condition in the if.
  • (.*?) ensures that it will grab as little content as possible.
  • It worked perfectly, now I’m getting it!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.