Home » PHP htmlspecialchars() Function

PHP htmlspecialchars() Function

by Online Tutorials Library

PHP String htmlspecialchars() Function

The htmlspecialchars() function converts special characters into HTML entities. It is the in-built function of PHP, which converts all pre-defined characters to the HTML entities. The pre-defined characters are:

  • & (ampersand) converted as &
  • “ (double quote) converted as "
  • ‘ (single quote) converted as '
  • < (less than) converted as &lt;
  • > (greater than) converted as &gt;

There is a string function htmlspecialchars_decode(), which is reverse of the htmlspecialchars() function. The main purpose of htmlspecialchars_decode() function is to convert special HTML entities back to characters. htmlspecialchars() and htmlspecialchars_decode() function are opposite to each other. The syntax of the htmlspecialchars() function is given below:

Syntax:

Parameters

$string: This parameter is contains the input string.

$flags: Basically, this parameter is used to hold the one or more flags from following, which specify how to handle invalid code unit sequences, quotes, and the used document type. ENT_COMPAT | ENT_HTML401 is by default. The available flags constants are given below in the table:

Available flags constants

Constant Name Description
ENT_IGNORE It discards invalid code unit sequence instead of returning an empty string. ENT_QUOTES It converts both single and double-quotes. ENT_NOQUOTES It does not convert any string as it leaves both single and double-quotes unconverted. ENT_SUBSTITUDE It replaces invalid code unit sequence with Unicode replacement character U+FFFD (UTF-8) or &#FFFD instead of returning an empty string. ENT_DISALLOWED Instead of leaving the invalid code points as it is, it replaces them for the given document type with a Unicode Replacement Character. ENT_HTML401 It handles code as HTML 4.01 version. ENT_XML1 It handles code as XML 1. ENT_XHTML It handles code as XHTML. ENT_HTML5 It handles code as HTML5.

You may also like