Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/267.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 在Pre标记中转义HTML字符_Php_Html_Replace_Pre - Fatal编程技术网

Php 在Pre标记中转义HTML字符

Php 在Pre标记中转义HTML字符,php,html,replace,pre,Php,Html,Replace,Pre,我已经安装了语法荧光灯,但为了使其工作,标记必须写成和。我需要做的是替换所有tl;博士 您需要解析输入的HTML。使用该类表示文档,解析输入,查找所有 function escapeRecursively($node) { if ($node instanceof DOMText) return $node->textContent; $children = $node->childNodes; $content = "<$node-&

我已经安装了语法荧光灯,但为了使其工作,标记必须写成
。我需要做的是替换所有tl;博士 您需要解析输入的HTML。使用该类表示文档,解析输入,查找所有

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>";
}
现在,此函数可用于转义文档中的每个
节点:

<!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 &lt;em&gt;interesting&lt;/em&gt; text</pre></body></html>
函数EscapePreformatedCode($html){
$doc=新的DOMDocument();
$doc->loadHTML($html);
$pres=$doc->getElementsByTagName('pre');
对于($i=0;$i<$pres->length;$i+=1){
$node=$pres->item($i);
$children=$node->childNodes;
$content='';
对于($j=0;$j<$children->length;$j+=1){
$child=$children->item($j);
$content.=逐次转义($child);
}
$node->nodeValue=htmlspecialchars($content);
}
返回$doc->saveHTML();
}
试验
$string='测试一些有趣的文本';
echo转义预定义代码($string);
收益率:


测试一些有趣的/em文本

请注意,DOM始终表示完整的文档。因此,当DOM解析器获得一个文档片段时,它会填充缺少的信息。这使得输出可能与输入不同。

我不确定是否理解-您是否试图转义HTML代码以在页面上显示它?是的,但仅在“pre”标记内部。在
回送
标记之前,对标记的内容使用
htmlspecialchars
。这就是你在回显之前应该做的事情。@Jon但我如何仅在pre标记中使用它?如果你使用了MVC模式,那么在你的代码中,你应该确切地知道它在视图中输出标记的位置,并且能够添加
htmlspecialchars
非常简单的标记!除了一个小错误外,工作正常。这在我加载页面时显示:/www.w3.org/TR/REC-html40/loose.dtd“>@Terry那么你在加载哪个页面?我的示例代码在浏览器中显示得很好。我对它进行了测试,它只在我添加代码时出现。@Terry尽管如此,我很有信心错误在别处,只是通过添加我的代码被清除了。它是独立工作的。我真的不能再说了,因为我不知道你的密码。
$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 &lt;em&gt;interesting&lt;/em&gt; text</pre></body></html>