PHP将字符串转换为htmlentities [英] PHP convert string to htmlentities
问题描述
如何将<code>
和<pre>
标记内的代码转换为html实体?
How can I convert the code inside the <code>
and <pre>
tags to html entities ?
<code class="php"> <div> a div.. </div> </code>
<pre class="php">
<div> a div.. </div>
</pre>
<div> this should be ignored </div>
推荐答案
好的,我已经玩了一段时间了.结果可能不是最好或最直接的解决方案(坦率地说,如果有任意用户要提交输入,我完全不同意您的方法),但它似乎有效".而且,最重要的是,它不使用正则表达式来解析XML. :)
OK, I've been playing with this for a while. The result may not be the best or most direct solution (and, frankly, I disagree with your approach entirely if arbitrary users are going to be submitting the input), but it appears to "work". And, most importantly, it doesn't use regexes for parsing XML. :)
使输入无效
<?php
$str = <<<EOF
<code class="php"> <div> a div.. </div> </code>
<pre class="php">
<div> a div.. </div>
</pre>
<div> this should be ignored </div>
EOF;
?>
代码
<?php
function recurse(&$doc, &$parent) {
if (!$parent->hasChildNodes())
return;
foreach ($parent->childNodes as $elm) {
if ($elm->nodeName == "code" || $elm->nodeName == "pre") {
$content = '';
while ($elm->hasChildNodes()) { // `for` breaks the `removeChild`
$child = $elm->childNodes->item(0);
$content .= $doc->saveXML($child);
$elm->removeChild($child);
}
$elm->appendChild($doc->createTextNode($content));
}
else {
recurse($doc, $elm);
}
}
}
// Load in the DOM (remembering that XML requires one root node)
$doc = new DOMDocument();
$doc->loadXML("<document>" . $str . "</document>");
// Iterate the DOM, finding <code /> and <pre /> tags:
recurse($doc, $doc->documentElement);
// Output the result
foreach ($doc->childNodes->item(0)->childNodes as $node) {
echo $doc->saveXML($node);
}
?>
输出
<code class="php"> <div> a div.. </div> </code>
<pre class="php">
<div> a div.. </div>
</pre>
<div> this should be ignored </div>
证明
您可以在此处看到它.
请注意,它不会显式调用htmlspecialchars
; DOMDocument
对象可以自行处理转义.
Note that it doesn't explicitly call htmlspecialchars
; the DOMDocument
object handles the escaping itself.
我希望这会有所帮助. :)
I hope that this helps. :)
这篇关于PHP将字符串转换为htmlentities的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!