htmlspecialchars is an extremely useful PHP function. Its use is defined by the PHP manual as such:
Certain characters have special significance in HTML, and should be represented by HTML entities if they are to preserve their meanings. This function returns a string with some of these conversions made; the translations made are those most useful for everyday web programming…
This function is useful in preventing user-supplied text from containing HTML markup, such as in a message board or guest book application.
The translations performed are:
‘&’ (ampersand) becomes ‘&’
‘“’ (double quote) becomes ‘"’…
‘<’ (less than) becomes ‘<’
‘>’ (greater than) becomes ‘>’
This function proves useful in languages other than just PHP. It is necessary to use these HTML entities whenever you want HTML to display as plain text instead of being parsed, in whatever language you may be using to output it.
<strong>command</strong> would display as command instead of as what they entered. It is precisely situations like this that
htmlspecialchars was invented.
<strong>command</strong>, and converts its HTML entities, resulting in
<strong>command</strong>. This allows it to be output safely.
I will also include
htmlspecialchars_decode for converting a string of HTML entities back to its original HTML markup.
A Reversed Array
Those of you with a keen eye may have noticed that the
specialchars array for decoding is reverse of the one for encoding. This is both deliberate and necessary.
The ampersand (
&) must be translated before the other three due to the fact that the other HTML entities include ampersands! If the other entities were to translate first, their ampersands would translate too.
This same logic applies to decoding HTML entities. If ampersands are the first to translate going forward, they must be the last to translate in reverse. Otherwise, you risk double-decoding an HTML entity, resulting in the wrong string.
This code, being so short, is free for you to use and distribute. You are welcome to leave feedback in the comments or reach out to me on Twitter or through any of the contact options available at CharlesStover.com.