What are the differences between htmlspecialchars()and htmlentities(). When should I use one or the other?Explain me in poor words

Member Avatar

From the manual - htmlspecialchars:

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 these conversions made. If you require all input substrings that have associated named entities to be translated, use htmlentities() instead.

This function just does this:

'&' (ampersand) becomes '&'
'"' (double quote) becomes '"' when ENT_NOQUOTES is not set.
"'" (single quote) becomes ''' (or ') only when ENT_QUOTES is set.
'<' (less than) becomes '&lt;'
'>' (greater than) becomes '&gt;'

These are the ONLY characters that will be encoded by htmlspecialchars


From the manual - htmlentities:

This function is identical to htmlspecialchars() in all ways, except with htmlentities(), all characters which have HTML character entity equivalents are translated into these entities.

So this will also encode things like ô, ï etc. - anything that has a "HTML entity equivalent"

Thanks sir. which is good for to use in chat ?

Member Avatar

Depends on your implementation. Show your code and we'll see. I was assumming that you were using PHP, but noticed that you've posted to the JS forum. So bit confused.