Skip to content Skip to sidebar Skip to footer

Php Convert String To Htmlentities

How can I convert the code inside the and
 tags to html entities ? 
a div..

Faking the input

<?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;

?>

Code

<?phpfunctionrecurse(&$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 resultforeach ($doc->childNodes->item(0)->childNodes as$node) {
   echo$doc->saveXML($node);
}

?>

Output

<codeclass="php">&lt;div&gt; a div.. &lt;/div&gt;</code><preclass="php">&lt;div&gt; a div.. &lt;/div&gt;</pre><div> this should be ignored </div>

Proof

You can see it working here.

Note that it doesn't explicitly call htmlspecialchars; the DOMDocument object handles the escaping itself.

I hope that this helps. :)

Solution 2:

You can use jquery. This will encode anything inside any tags with a class code.

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

The fiddle: http://jsfiddle.net/mazzzzz/qnbLL/

Solution 3:

PHP

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

HTML

<codeclass="php">&lt;div&gt; a div.. &lt;/div&gt;</code><preclass="php">&lt;div&gt; a div.. &lt;/div&gt;</pre><div> this should be ignored </div>

Have you ever heard of BB code? http://en.wikipedia.org/wiki/BBCode

Solution 4:

This is related somewhat, you do not have to use Geshi, but I wrote a bit of code here Advice for implementing simple regex (for bbcode/geshi parsing) that would help you with the problem.

It can be tweaked to not use GeSHi, just would take a bit of tinkering. Hope it helps ya.

Post a Comment for "Php Convert String To Htmlentities"