htmlentities
(PHP 4, PHP 5, PHP 7, PHP 8)
Convert all applicable characters to HTML entities
Description
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. The get_html_translation_table() function can be used to return the translation table used dependent upon the provided flags constants.
If you want to decode instead (the reverse) you can use html_entity_decode().
Parameters
stringThe input string.
flagsA bitmask of one or more of the following flags, which specify how to handle quotes, invalid code unit sequences and the used document type. The default is
ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401.Constant Name Description ENT_COMPATWill convert double-quotes and leave single-quotes alone. ENT_QUOTESWill convert both double and single quotes. ENT_NOQUOTESWill leave both double and single quotes unconverted. ENT_IGNORESilently discard invalid code unit sequences instead of returning an empty string. Using this flag is discouraged as it may have security implications. ENT_SUBSTITUTEReplace invalid code unit sequences with a Unicode Replacement Character U+FFFD (UTF-8) or &#FFFD; (otherwise) instead of returning an empty string. ENT_DISALLOWEDReplace invalid code points for the given document type with a Unicode Replacement Character U+FFFD (UTF-8) or &#FFFD; (otherwise) instead of leaving them as is. This may be useful, for instance, to ensure the well-formedness of XML documents with embedded external content. ENT_HTML401Handle code as HTML 4.01. ENT_XML1Handle code as XML 1. ENT_XHTMLHandle code as XHTML. ENT_HTML5Handle code as HTML 5. encodingEncoding Charsets
double_encodeWhen
double_encodeis turned off PHP will not encode existing html entities. The default is to convert everything.
Return Values
Returns the encoded string.
If the input string contains an invalid code unit sequence within the given encoding an empty string will be returned, unless either the ENT_IGNORE or ENT_SUBSTITUTE flags are set.
Changelog
| Version | Description |
|---|---|
| 8.1.0 | flags changed from ENT_COMPAT to ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401. |
| 8.0.0 | encoding is nullable now. |
Examples
A htmlentities() example
<?php
$str = "A 'quote' is <b>bold</b>";
echo htmlentities($str);
echo "\n\n";
echo htmlentities($str, ENT_COMPAT);
?>The above example will output:
A 'quote' is <b>bold</b>
A 'quote' is <b>bold</b>Usage of ENT_IGNORE
<?php
$str = "\x8F!!!";
// Outputs an empty string
echo htmlentities($str, ENT_QUOTES, "UTF-8");
// Outputs "!!!"
echo htmlentities($str, ENT_QUOTES | ENT_IGNORE, "UTF-8");
?>