2

I want to have a regex pattern to evaluate the if/else in manually-created html tags like this:

<if condition="$condition">
    Return value if true
<else/>
    Return value if false
</if>

And, more specifically:

<if condition="$condition">
    Return value if true
<elseif condition="$another_condition"/>
    Return value if the above is true
<elseif condition="$more_condition"/>
    Return value if the above is true
<else/>
    Return value if non of the above is true
</if>

Basically, I want to get the backreferences return values of all 'conditions', and 'return values' for practicing of php variable printing to html file. Example:

  • In the first one, $2 is the $condition, $3 is the return value if true, $4 if false
  • In the second one, $2 is the $condition, $3 is if true, $4 is the 2nd condition, $5 is return value of the above condition if matched, and so on.

I need a pattern that can either regconize if there are any

<else/>

or

<else condition="blah">

or multiple appearances of it, to return properly backreferences' values.

The purpose of this is to use a php file (with predefined variables) to include a html template, and print out values to it based on php variable, without directly using

<?php if ($condition) { $result; } ?>

inside the html template.

Example:

PHP file:

<?php

  function callback()
  {
    $precondition  = eval('return ' . $matches[1] . ';');

    // Prewritten function for parsing boolean from string
    $condition = parse_boolean($precondition); 


    // Restrict result to boolean only
    if (is_bool($condition))
    {
        // This need better coding based on multiple <elseif ../>
        $ret = ($condition ? $matches[2] : $matches[4]);
    }

    return $ret;      
  }

  $a = 5;
  $b = 6;

  $content = file_get_contents('/html/file/path.html');

  $pattern = 'I need this pattern';
  $output  = preg_replace_callback($pattern, 'callback', $content);

  echo $output;
?>

HTML file:

<if condition="$a == $b">
    a is equal with b
<elseif condition="$a > $b">
    a is larger than b
<elseif condition="$a < $b">
    a is smaller than b
</if>

When running the PHP file, it will print:

a is smaller than b

I hope to get a specific answer, or any else ways to fix the codes that I've written myself (not really good imho).

Thank you.

Tsuki
  • 33
  • 5

2 Answers2

1

Try something like this:

PHP

$file = file_get_contents('regexhtml.html');
$html = new DOMDocument();
$html->loadHTMLFile('regexhtml.html');

$conditions = array();
$matches = array();

$ifs = $html->getElementsByTagName('cond');

foreach ($ifs as $if_s) {
     // If
     $ifs1 = $if_s->getElementsByTagName('if');

     $counter = 0;
     foreach ($ifs1 as $if_s1) {
        $conditions[count($conditions)]['if_'.$counter] = array(
            'condition' => $if_s1->getAttribute('condition'),
            'message' => trim($if_s1->nodeValue)
        );
        $counter++;
     }


     // Else-if
     $ifs2 = $if_s->getElementsByTagName('elseif');

     $counter = 0;
     foreach ($ifs2 as $if_s2) {
        $conditions[count($conditions)]['elseif_'.$counter] = array(
            'condition' => $if_s2->getAttribute('condition'),
            'message' => trim($if_s1->nodeValue)
        );
        $counter++;
     }

     // Else
     $ifs3 = $if_s->getElementsByTagName('else');

     $counter = 0;
     foreach ($ifs3 as $if_s3) {
        $conditions[count($conditions)]['else_'.$counter] = array(
            'message' => trim($if_s1->nodeValue)
        );
        $counter++;
     }
}

echo '<pre>';
print_r($conditions);
echo '</pre>';

You will get some warnings tho, so do error_reporting('E_NONE'); to ignore the invalid HTML warnings. As long as you have xHTML/HTML5 complaint browsers it should support custom tags.

HTML (regexhtml.html)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Title</title>
</head>
<body>
    <cond>
        <if condition="$a == $b">
            a is equal with b
        </if>
        <elseif condition="$a > $b">
            a is larger than b
        </elseif>
        <elseif condition="$a < $b">
            a is smaller than b
        </elseif>
        <else>
            a is smaller than b
        </else>
    </cond>
</body>
</html>

Output

Array
(
    [0] => Array
        (
            [if_0] => Array
                (
                    [condition] => $a == $b
                    [message] => a is equal with b
                )

        )

    [1] => Array
        (
            [elseif_0] => Array
                (
                    [condition] => $a > $b
                    [message] => a is equal with b
                )

        )

    [2] => Array
        (
            [elseif_1] => Array
                (
                    [condition] => $a < $b
                    [message] => a is equal with b
                )

        )

    [3] => Array
        (
            [else_0] => Array
                (
                    [message] => a is equal with b
                )

        )

)

You can now do with the output whatever you like. Strip it to make regex or whatever you wish to do with it.

To match the PHP variables (like $a) you may need some scope manipulation;

// These won't practically exist, but only as strings in the Array() object
$html_a1 = '12';
$html_b1 = '23';

// Storing the string-based code into new variables
$a1 = eval('return $html_a1;');
$b1 = eval('return $html_b1;');

echo eval('return $html_a1;').'<br /><br />';

if ($a1 == $b1) {
    echo 'a is equal with b';
}
elseif ($a1 > $b1) {
    echo 'a is larger than b';
}
elseif ($a1 < $b1) {
    echo 'a is smaller than b';
}
else {
    echo 'Something else';
}

With the DOMDocument() library you can write back the outcomes instantly too if you need (http://www.php.net/manual/en/class.domdocument.php), so you won't need to rebuild your HTML manually. The library also allows you to write-back the manipulated HTML.

Good luck!

0

Maybe this will help you, I used preg_replace() with multiple patterns, I'm assuming that you trust the one who's creating the "HTML file":

$a = 5;
$b = 7;
$html = '<if condition="$a == $b">
    a is equal with b
<elseif condition="$a > $b">
    a is larger than b
<elseif condition="$a < $b">
    a is smaller than b
</if>';

$new_html = preg_replace(array('/<if condition="(.*)">\s*(.*)/', '/<elseif condition="(.*)">\s*(.*)/', '/<\/if>/'), array('if($1){'.PHP_EOL.'echo "$2";', '}elseif($1){'.PHP_EOL.'echo "$2";', '}'), $html);
eval($new_html); // result
var_dump($new_html); // This is to view the "final" code
HamZa
  • 14,671
  • 11
  • 54
  • 75