PHP htmlspecialchars() Function
The PHP htmlspecialchars() function converts some predefined characters to HTML entities. The predefined characters are:
- & (Ampersand) becomes &
- " (Double quote) becomes ", unless ENT_NOQUOTES is set
- ' (Single quote) becomes ' (for ENT_HTML401) or ' (for ENT_XML1, ENT_XHTML or ENT_HTML5), but only when ENT_QUOTES is set
- < (Less than) becomes <
- > (Greater than) becomes >
Note: This function translates only the above listed entity. For full entity translation, htmlentities() function can be used.
Syntax
htmlspecialchars(string, flags, encoding, double_encode)
Parameters
string |
Required. Specify the input string. |
flags |
Optional. Specify how to handle quotes, invalid code unit sequences and the used document type. The available flags constants are:
|
encoding |
Optional. A string that specifies which character-set to use. The following character sets are supported:
|
double_encode |
Optional. If set to false, PHP will not encode existing html entities. The default is true which converts everything. |
Return Value
Returns the encoded string. If the input string contains an invalid code unit sequence within the given encoding an empty string is returned, unless either the ENT_IGNORE or ENT_SUBSTITUTE flags are set.
Example:
The example below shows the usage of htmlspecialchars() function.
<?php $str = "<a href='test'>Test</a>"; //returns: <a href='test'>Test</a> echo htmlspecialchars($str, ENT_QUOTES); ?>
The output of the above code will be:
<a href='test'>Test</a>
Note: In case of an ambiguous flags value, the following rules apply:
- When neither of ENT_COMPAT, ENT_QUOTES, ENT_NOQUOTES is present, the default is ENT_NOQUOTES.
- When more than one of ENT_COMPAT, ENT_QUOTES, ENT_NOQUOTES is present, ENT_QUOTES takes the highest precedence, followed by ENT_COMPAT.
- When neither of ENT_HTML401, ENT_HTML5, ENT_XHTML, ENT_XML1 is present, the default is ENT_HTML401.
- When more than one of ENT_HTML401, ENT_HTML5, ENT_XHTML, ENT_XML1 is present, ENT_HTML5 takes the highest precedence, followed by ENT_XHTML, ENT_XML1 and ENT_HTML401.
- When more than one of ENT_DISALLOWED, ENT_IGNORE, ENT_SUBSTITUTE are present, ENT_IGNORE takes the highest precedence, followed by ENT_SUBSTITUTE.
❮ PHP String Reference