簡體   English   中英

PHP將字符串轉換為htmlentities

[英]PHP convert string to htmlentities

如何將<code><pre>標記內的<code>轉換為html實體?

<code class="php"> <div> a div.. </div> </code>

<pre class="php">
<div> a div.. </div>
</pre>

<div> this should be ignored </div>

您可以使用jquery。 這將使用類code對任何標簽內的所有內容進行code

$(".code").each(
    function () {
        $(this).text($(this).html()).html();
    }
);

小提琴: http//jsfiddle.net/mazzzzz/qnbLL/

的PHP

if(preg_match_all('#\<(code|pre) class\=\"php\"\>(.*?)\</(code|pre)\>#is', $html, $code)){
    unset($code[0]);
    foreach($code as $array){
        foreach($array as $value){
            $html = str_replace($value, htmlentities($value, ENT_QUOTES), $html);
        }
    }
}

的HTML

<code class="php"> &lt;div&gt; a div.. &lt;/div&gt; </code>

<pre class="php">
&lt;div&gt; a div.. &lt;/div&gt;
</pre>

<div> this should be ignored </div>

您聽說過BB代碼嗎? http://en.wikipedia.org/wiki/BBCode

好的,我已經玩了一段時間了。 結果可能不是最佳或最直接的解決方案(坦率地說,如果有任意用戶要提交輸入,我完全不同意您的方法),但它似乎“有效”。 而且,最重要的是,它不使用正則表達式來解析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"> &lt;div&gt; a div.. &lt;/div&gt; </code>

<pre class="php">
&lt;div&gt; a div.. &lt;/div&gt;
</pre>

<div> this should be ignored </div>

證明

您可以看到它在這里工作。

注意,它沒有顯式調用htmlspecialchars DOMDocument對象處理轉義本身。

我希望這個對你有用。 :)

這有點相關,您不必使用Geshi,但是我在這里寫了一些代碼來實現簡單的正則表達式(用於bbcode / geshi解析)的建議 ,可以幫助您解決該問題。

可以不使用GeSHi進行調整,只是需要一些修補。 希望對您有幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM