What are the differences between htmlspecialchars()
and htmlentities()
. When should I use one or the other?
The differences between htmlspecialchars() and htmlentities() is very small. Lets see some examples:
htmlspecialchars
htmlspecialchars(string $string) takes multiple arguments where as the first argument is a string and all other arguments (certain flags, certain encodings etc. ) are optional. htmlspecialchars converts special characters in the string to HTML entities. For example if you have < br > in your string, htmlspecialchars will convert it into < b >. Whereas characters like µ † etc. have no special significance in HTML. So they will be not converted to HTML entities by htmlspecialchars function as shown in the below example.
echo htmlspecialchars('An example
'); // This will print - An example < br >
echo htmlspecialchars('µ †'); // This will print - µ †
htmlentities
htmlentities ( string $string) is very similar to htmlspecialchars and takes multiple arguments where as the first argument is a string and all other arguments are optional (certain flags, certain encodings etc.). Unlike htmlspecialchars, htmlentities converts not only special characters in the string to HTML entities but all applicable characters to HTML entities.
echo htmlentities('An example
'); // This will print - An example < br >
echo htmlentities('µ †'); // This will print - µ †