我想要一个正则表达式模式来评估手动创建的 html 标签中的 if/else,如下所示:
<if condition="$condition">
Return value if true
<else/>
Return value if false
</if>
而且,更具体地说:
<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>
基本上,我想获取所有“条件”的反向引用返回值,以及“返回值”,以练习将 php 变量打印到 html 文件。例子:
- 在第一个中,$2 是 $condition,$3 是返回值,如果为真,则为 $4,如果为假
- 在第二个中,$2 是 $condition,$3 是如果为真,$4 是第二个条件,$5 是上述条件如果匹配的返回值,以此类推。
我需要一个可以重新调整的模式(如果有的话)
<else/>
或者
<else condition="blah">
或多次出现,以正确返回反向引用的值。
这样做的目的是使用一个 php 文件(带有预定义变量)来包含一个 html 模板,并根据 php 变量将值打印出来,而不是直接使用
<?php if ($condition) { $result; } ?>
在 html 模板中。
例子:
PHP 文件:
<?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 文件:
<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>
运行 PHP 文件时,它将打印:
a is smaller than b
我希望得到一个具体的答案,或者任何其他方法来修复我自己编写的代码(不是很好恕我直言)。
谢谢你。