PHP – Convert special character &quot to real quote

In certain situations, you couldĀ be messing with HTML special characters in a text. At first glance, you might not even notice these are existing in the text. For example, if you’re looking text in a browser these characters will look just like normal characters. But when you peak into the page source you’ll see very different representations, (&amp; for &, &quot; for “, &lt; for <, &gt for > and so on). So how do you convert it to the normal characters?

First, you need to find out why the normal characters are converted to these special entities. Most of the times the main reason is conflicting with some transport protocols or incompatibility with some database standards. But in recent times it’s just a developer’s habit to “escape” everything even if it’s not really needed. Just in a case.

So now when you confirm that nothing will break when you convert it back we can do it quite easily. There’s PHP function, htmlspecialchars_decode which is doing exactly what we need, so there’s no need to hack around:

$clean_text = htmlspecialchars_decode($text);

If you need to convert only one specific entity you can use our old friend str_replace function, like this:

$no_nbsp_text = str_replace("&quot;", "\"", $text);

It’s also possible to do the same with regular expression functions but there’s no need to complicate our life more than it already is.

Leave a Reply

Your email address will not be published. Required fields are marked *