Deep Tech Point
first stop in your tech adventure
Home / PHP
PHP – Convert special character &quot to real quote
January 18, 2021 | PHP

You could come into a situation where you are dealing with HTML special characters in some text. Ordinary users might not even notice these special characters exist because when they take a peek at a text in a browser these characters look exactly like normal characters do. However, if you – an advanced user – take a look into the page source, you’ll notice some very unusual presentations, (&amp; for &, &quot; for “, &lt; for <, &gt for > and so on). So, the question is – how do you convert this mumbo jumbo to normal characters?

The first step would be getting familiar with why are normal characters transformed into these special units. In the vast majority of cases, the main reason is clashing with some transport protocols or is simply incompatible with some specific database standards. However, lately, this special character conversion has become a developer’s habit to avoid just about every single thing, especially if it’s not really needed. Just in a case.

So now, when you are sure that you are safe and hell will not break loose when you convert these special characters, believe me, you can do it quite easily. There’s this PHP function, htmlspecialchars_decode which is dedicated to the exact thing we need, so there’s absolutely no need to hack around:

$clean_text = htmlspecialchars_decode($text);

And if you’re aiming at changing only one specific entity, you can absolutely use our old friend str_replace function, like this:

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

Keep in mind it is also possible to perform the same expression with regular expression functions, but I believe there’s no need to complicate your life more than it already is.