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.