Pritom
Pritom

Reputation: 1333

Html entities back to special characters with php

I want to convert special characters to HTML entities, and then back to the original characters.

I have used htmlentities() and then html_entity_decode(). It worked fine for me, but { and } do not come back to the original characters, they remain { and }.

What can I do now?

My code looks like:

$custom_header = htmlentities($custom_header);
$custom_header = html_entity_decode($custom_header);

Upvotes: 0

Views: 1336

Answers (1)

nickb
nickb

Reputation: 59709

Even though nobody can replicate your problem, here's a direct way to solve it by a simple str_replace.

$input = '<p><script type="text/javascript"> $(document).ready(function() &#123; $("#left_side_custom_image").click(function() &#123; alert("HELLO"); &#125;); &#125;); </script></p> ';
$output = str_replace( array( '&#123;', '&#125;'), array( '{', '}'), $input);

Demo (click the 'Source' link in the top right)

Edit: I see the problem now. If your input string is:

"&#123;hello}"

A call to htmlentities encodes the & into &amp;, which gives you the string

"&amp;#123;hello}"

The &amp; is then later decoded back into &, to output this:

"&#123;hello}"

The fix is to send the string through html_entity_decode again, which will properly decode your entities.

$custom_header = "&#123;hello}";
$custom_header = htmlentities($custom_header);

$custom_header = html_entity_decode($custom_header);
echo html_entity_decode( $custom_header); // Outputs {hello}

Upvotes: 2

Related Questions