Category Archives: htmlspecialchars vs htmlentities

htmlspecialchars vs htmlentities

From the PHP documentation for 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.

From the PHP documentation for 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 some of these conversions made; the translations made are those most useful for everyday web programming. If you require all HTML character entities to be translated, use htmlentities() instead.

While htmlspecialchars converts only 5 special characters to html entities, htmlentities converts all characters which have HTML character entity equivalents.

Example

htmlentities

PHP CODE:
<?php
$str = "A 'quote' is <b>bold</b>";

echo htmlentities($str);
echo htmlentities($str, ENT_QUOTES);
?>

OUTPUT

A 'quote' is &lt;b&gt;bold&lt;/b&gt;

A &#039;quote&#039; is &lt;b&gt;bold&lt;/b&gt;

htmlspecialchars

PHP CODE:

<?php
$new = htmlspecialchars("<a href='test'>Test</a>", ENT_QUOTES);
echo $new; //
?>

OUTPUT


&lt;a href=&#039;test&#039;&gt;Test&lt;/a&gt;

Sources:
stackoverflow
Wallpaperama
Webune
Php Freaks