我已经安装了语法高亮显示器,但为了使其正常工作,标签必须写为<
和>
。我需要做的是将<
和&gt;的所有&lt;'替换为>
,但仅在PRE标记内。
因此,简而言之,我想要转义pre标签内的所有HTML字符。
提前致谢。
答案 0 :(得分:2)
您需要解析输入HTML。使用DOMDocument
类来表示您的文档,解析输入,找到所有<pre>
标记(使用findElementsByTagName
)并转义其内容。
不幸的是,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();
}
$string = '<h1>Test</h1> <pre>Some <em>interesting</em> text</pre>';
echo escapePreformattedCode($string);
收率:
<!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始终代表完整的文档。因此,当DOM解析器获取文档片段时,它会填充缺少的信息。这使输出可能与输入不同。