您正在用模式本身替换匹配,您没有使用反向引用和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));
这只是保持简单,而且几乎肯定会更快。