htmlentities()
htmlentities() — Convert all applicable characters to HTML entities.
Built-in function of PHP 8.5. The manual lists it as available in PHP 4, PHP 5, PHP 7, PHP 8. This page is the reference card: signature, parameters and return value, plus the changelog and the example the manual provides.
What it does
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.
Signature
htmlentities(string $string, int $flags = ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401, ?string $encoding = null, bool $double_encode = true): string
Parameters
| Parameter | Type | What it takes |
|---|---|---|
| $string | string | The input string. |
| $flags | int | A 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. Available flags constants Constant Name Description 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 ... |
| $encoding | ?string | The following character sets are supported: Supported charsets Charset Aliases Description ISO-8859-1 ISO8859-1 Western European, Latin-1. ISO-8859-5 ISO8859-5 Little used cyrillic charset (Latin/Cyrillic). ISO-8859-15 ISO8859-15 Western European, Latin-9. Adds the Euro sign, French and Finnish letters missing in Latin-1 (ISO-8859-1). UTF-8 ASCII compatible multi-byte 8-bit Unicode. cp866 ibm866, 866 DOS-specific ... |
| $double_encode | bool | When double_encode is turned off PHP will not encode existing html entities. The default is to convert everything. |
Return value
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.
Example
A runnable snippet:
$str = "A 'quote' is <b>bold</b>"; echo htmlentities($str); echo "\n\n"; echo htmlentities($str, ENT_COMPAT);
Output:
A 'quote' is <b>bold</b> A 'quote' is <b>bold</b>
Changelog
| Version | Change |
|---|---|
| 8.1.0 | flags changed from ENT_COMPAT to ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401. |
| 8.0.0 | encoding is nullable now. |
See also
html_entity_decode(), get_html_translation_table(), htmlspecialchars(), nl2br(), urlencode()
All PHP 8.5 built-in functions
Reference card built from the PHP manual page htmlentities() (PHP documentation, CC BY 3.0). The page is generated from the manual, so the wording of the parameter and return value text follows php.net.