tl;dr
您需要解析输入的 HTML。使用DOMDocument http://docs.php.net/manual/en/class.domdocument.php类来表示您的文档,解析输入,查找所有<pre>
标签(使用findElementsByTagName http://docs.php.net/manual/en/domdocument.getelementsbytagname.php)并转义其内容。
Code
不幸的是,DOM 模型非常低级,迫使您迭代<pre>
给自己贴上标签,以逃避他们。这看起来如下:
function escapeRecursively($node) {
if ($node instanceof DOMText)
return $node->textContent;
$children = $node->childNodes;
$content = "<$node->nodeName>";
for ($i = 0; $i < $children->length; $i += 1) {
$child = $children->item($i);
$content .= escapeRecursively($child);
}
return "$content</$node->nodeName>";
}
现在这个函数可以用来转义每一个<pre>
文档中的节点:
function escapePreformattedCode($html) {
$doc = new DOMDocument();
$doc->loadHTML($html);
$pres = $doc->getElementsByTagName('pre');
for ($i = 0; $i < $pres->length; $i += 1) {
$node = $pres->item($i);
$children = $node->childNodes;
$content = '';
for ($j = 0; $j < $children->length; $j += 1) {
$child = $children->item($j);
$content .= escapeRecursively($child);
}
$node->nodeValue = htmlspecialchars($content);
}
return $doc->saveHTML();
}
Test
$string = '<h1>Test</h1> <pre>Some <em>interesting</em> text</pre>';
echo escapePreformattedCode($string);
Yields:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html><body><h1>Test</h1> <pre>Some <em>interesting</em> text</pre></body></html>
请注意,DOM 始终代表一个complete文档。因此,当 DOM 解析器获取文档片段时,它会填充缺失的信息。这使得输出可能与输入不同。