Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inverse htmlentities / html_entity_decode

Basically I want to turn a string like this:

<code> &lt;div&gt; blabla &lt;/div&gt; </code>

into this:

&lt;code&gt; <div> blabla </div> &lt;/code&gt;

How can I do it?


The use case (bc some people were curious):

A page like this with a list of allowed HTML tags and examples. For example, <code> is a allowed tag, and this would be the sample:

<code>&lt;?php echo "Hello World!"; ?&gt;</code>

I wanted a reverse function because there are many such tags with samples that I store them all into a array which I iterate in one loop, instead of handling each one individually...

like image 222
Alex Avatar asked Jul 12 '11 17:07

Alex


1 Answers

My version using regular expressions:

$string = '<code> &lt;div&gt; blabla &lt;/div&gt; </code>';
$new_string = preg_replace(
    '/(.*?)(<.*?>|$)/se', 
    'html_entity_decode("$1").htmlentities("$2")', 
    $string
);

It tries to match every tag and textnode and then apply htmlentities and html_entity_decode respectively.

like image 51
Karolis Avatar answered Sep 20 '22 16:09

Karolis