PHP htmlspecialchars() Function


The htmlspecialchars() function converts some predefined characters into HTML entities. To convert special HTML entities to characters, use the htmlspecialchars_decode() function.

  • & (ampersand) becomes &
  • "(double quotation marks)" becomes "
  • '(single quote) becomes '
  • <(less than) becomes &lt;
  • >(greater than) becomes &gt;

Syntax
htmlspecialchars(string,flags,character-set,double_encode)
Parameters
Parameter Description
string (Required) Specify the string to convert.
flags (Optional) Specify how to handle quotation marks, invalid encoding, and the document type used.
  • ENT_COMPAT - Default. Encodes double quotes only
  • ENT_QUOTES - Encodes double and single quotes
  • ENT_NOQUOTES - Do not encode quotes.
  • ENT_IGNORE - The function ignores invalid encodings rather than returning an empty string. Avoid as it may affect security.
  • ENT_SUBSTITUTE - Do not encode quotes.
  • ENT_DISALLOWED - Do not encode quotes.
  • ENT_HTML401 - Default. Treat code as HTML 4.01
  • ENT_HTML5 - Treat code as HTML 5
  • ENT_XML1 - Treat code as XML 1
  • ENT_XHTML - Treat code as XHTML
character-set (Optional) A string indicating which character set to use.
  • UTF-8 - Standard. ASCII compatible multi-byte 8-bit Unicode
  • ISO-8859-1 - Western Europe
  • ISO-8859-15 - Western Europe (adds euro symbol + French and Finnish characters that were missing in ISO-8859-1)
  • cp866 - DOS-specific Cyrillic character set
  • cp1251 - Windows-specific Cyrillic character set
  • cp1252 - Windows-specific Western European character set
  • KOI8-R - Russian
  • BIG5 - Traditional Chinese, primarily used in Taiwan
  • GB2312 - Simplified Chinese, National Standard Character Set
  • BIG5-HKSCS - Big5 with Hong Kong extensions
  • Shift_JIS - Japanese
  • EUC-JP - Japanese
  • MacRoman - Character set used by Mac OS
double_encode (Optional) A Boolean value that indicates whether to encode existing HTML entities.
  • TRUE - Default. I'm going to rebuild everything
  • FALSE - Existing HTML entities will not be encoded
Example
<?php
$str = "The <u>Underline</u> text.";
$txt = htmlspecialchars_decode($str);
echo $txt;
?>

HTML Output

<html>
    <head>
    </head>
      <body>
          The &lt;u&gt;Underline&lt;/u&gt; text.
      </body>
</html>

Output

The Underline text.

Prev Next