如何在 php 中将 html 值和普通字符串拆分为不同的数组


How can I split html value and normal string into different array in php?

假设我有如下字符串:

"b<a=2<sup>2</sup>"

实际上这是一个公式。我需要在网页上显示此公式,但在 b 字符串隐藏之后,因为它被认为是损坏的锚标签。我尝试使用 htmlspecialchars 方法,但它以纯文本形式返回完整的字符串。我正在尝试使用一些正则表达式,但我只能在一些标签之间获取文本。

更新:

这似乎适用于以下公式:

"(c<a) = (b<a) = 2<sup>2</sup>"

即使使用这个公式:

"b<a=2<sup>2</sup>"

术来了:

<?php
$_string = "b<a=2<sup>2</sup>";
$string = "(c<a) = (b<a) = 2<sup>2</sup>";
$open_sup = strpos($string,"<sup>");
$close_sup = strpos($string,"</sup>");
$chars_array = str_split($string);
foreach($chars_array as $index => $char)
{
    if($index != $open_sup && $index != $close_sup)
    {
        if($char == "<")
        {
            echo "&lt;";
        }
        else{
            echo $char;
        }
    }
    else{
        echo $char;
    }
}

旧解决方案(不起作用)

也许这会有所帮助:

我尝试反斜杠字符,但它没有按预期工作。然后我试过这个:

<?php
$string = "b&lta=2<sup>2</sup>";
echo $string;
?>

使用

也许你可以给出这样的空格:

b < a = 2<sup>2</sup>

它不会消失标签,看起来更善解人意......

您可以尝试这种正则表达式方法,该方法应该跳过元素。

$regex = '/<(.*?)'h*.*>.+<'/'1>(*SKIP)(*FAIL)|(<|>)/';
$string = 'b<a=2<sup>2</sup>';
$string = preg_replace_callback($regex, function($match) {
    return htmlentities($match[2]);
}, $string);
echo $string;

输出:

b&lt;a=2<sup>2</sup>

PHP 演示:https://eval.in/507605
正则表达式101:https://regex101.com/r/kD0iM0/1