How to Convert Special Characters to HTML Entities - htmlspecialchars() Function

PHP String Functions

Certain characters have special significance in HTML, and should be represented by HTML entities if they are to preserve their meanings.

Special Characters

This function converts five special characters to their corresponding HTML entities:

  1. < (less than) - &lt;
  2. > (greater than) - &gt;
  3. & (ampersand) - &amp;
  4. " (double quote) - &quot;
  5. ' (single quote) - &#039; or &apos;

Syntax

htmlspecialchars(string $string, int $flags = ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401)

Flags

This specifies how to handle quotes, invalid code unit sequences and the used document type. The default is ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401.

  • ENT_COMPAT: Will convert double-quotes and leave single-quotes alone.
  • ENT_QUOTES: Will convert both double and single quotes.
  • ENT_NOQUOTES: Will leave both double and single quotes unconverted.

Example

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

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

htmlentities() Function

If you require all input substrings that have associated named entities to be translated, use htmlentities() instead. It converts all characters that have HTML character entity equivalents.

htmlspecialchars_decode() Function

This function converts special HTML entities back to characters. This function is the opposite of htmlspecialchars().

The converted entities are: &amp;, &quot; (when ENT_NOQUOTES is not set), &#039; (when ENT_QUOTES is set), &lt; and &gt;.