1
$text = "
<tag>
<html>
HTML
</html>
</tag>
";

我想用 htmlspecialchars() 替换标签内的所有文本。我试过这个:

$regex = '/<tag>(.*?)<\/tag>/s';
$code = preg_replace($regex,htmlspecialchars($regex),$text);

但它不起作用。我将输出作为正则表达式模式的 htmlspecialchars。我想用与正则表达式模式匹配的数据的 htmlspecialchars 替换它。我应该怎么办?

4

2 回答 2

2

您正在用模式本身替换匹配,您没有使用反向引用和e-flag,但在这种情况下,preg_replace_callback将是要走的路:

$code = preg_replace_callback($regex,'htmlspecialchars',$text);

这会将数学组传递给htmlspecialchars,并使用其返回值作为替换。这些组可能是一个数组,在这种情况下,您可以尝试:

function replaceCallback($matches)
{
    if (is_array($matches))
    {
        $matches = implode ('', array_slice($matches, 1));//first element is full string
    }
    return htmlspecialchars($matches);
}

或者,如果您的 PHP 版本允许:

preg_replace_callback($expr, function($matches)
{
    $return = '';
    for ($i=1, $j = count($matches); $i<$j;$i++)
    {//loop like this, skips first index, and allows for any number of groups
        $return .= htmlspecialchars($matches[$i]);
    }
    return $return;
}, $text);

尝试上述任何方法,直到找到可行的方法...顺便说一句,如果您要删除的只是<tag>and </tag>,为什么不选择更快的方法

echo htmlspecialchars(str_replace(array('<tag>','</tag>'), '', $text));

这只是保持简单,而且几乎肯定会更快。

在此处查看最快、最简单的操作方式

于 2013-08-02T13:49:29.057 回答
0

如果要隔离模式定义的实际内容,可以使用preg_match($regex,$text,$hits);. 这将为您提供一个命中数组,这些位位于模式中的括号之间,从 $hits[1] 开始,$hits[0] 包含整个匹配的字符串)。然后,您可以开始操作这些找到的匹配项,可能使用htmlspecialchars... 并将它们再次组合成$code.

于 2013-08-02T13:55:56.830 回答