用于使用 preg_replace_callback 评估 html 的 if/else 条件的 PHP 正则表达式模式

标签 php html regex preg-replace-callback

我想要一个正则表达式模式来评估手动创建的 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为true返回值,$4为false
  • 第二个,$2是$condition,$3是if true,$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

我希望得到一个具体的答案,或者任何其他方法来修复我自己编写的代码(恕我直言,这不是很好)。

谢谢。

最佳答案

尝试这样的事情:

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>';

您会收到一些警告,所以 error_reporting('E_NONE'); 会忽略无效的 HTML 警告。只要您有兼容 xHTML/HTML5 的浏览器,它就应该支持自定义标签。

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>

输出

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
                )

        )

)

您现在可以随心所欲地处理输出。剥离它以制作正则表达式或任何您想用它做的事情。

要匹配 PHP 变量(如 $a),您可能需要进行一些范围操作;

// 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';
}

使用 DOMDocument() 库,您也可以在需要时立即写回结果 (http://www.php.net/manual/en/class.domdocument.php),因此您无需手动重建 HTML。该库还允许您写回被操纵的 HTML。

祝你好运!

关于用于使用 preg_replace_callback 评估 html 的 if/else 条件的 PHP 正则表达式模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15601632/

相关文章:

php - MySQL 之前转义引号

php - 从服务器文件夹中删除图像

php数组下拉字段未插入数据库mysql

python - 是否可以在 django 项目的根目录下提供静态 html 页面?

java - 正则表达式一或两个特定字母

mysql - 如何使用正则表达式在 mysql 中显示数据库

php - 如何记录每个用户尝试登录的每个 IP 地址?

html - 按钮文本位置与浏览器不同

html - 在窗口调整大小之前激活 CSS 属性?

javascript - jQuery - 有条件地附加 HTML