htmlspecialchars()

htmlspecialchars() — Convert special 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

Certain characters have special significance in HTML, and should be represented by HTML entities if they are to preserve their meanings. This function returns a string with these conversions made. If you require all input substrings that have associated named entities to be translated, use htmlentities() instead.

Signature

htmlspecialchars(string $string, int $flags = ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401, ?string $encoding = null, bool $double_encode = true): string

Parameters

ParameterTypeWhat it takes
$stringstringThe string being converted.
$flagsintA 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?stringFor the purposes of this function, the encodings ISO-8859-1, ISO-8859-15, UTF-8, cp866, cp1251, cp1252, and KOI8-R are effectively equivalent, provided the string itself is valid for the encoding, as the characters affected by htmlspecialchars() occupy the same positions in all of these encodings.
$double_encodeboolWhen double_encode is turned off PHP will not encode existing html entities, the default is to convert everything.

Return value

The converted 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:

$new = htmlspecialchars("<a href='test'>Test</a>", ENT_QUOTES); echo $new; // &lt;a href=&#039;test&#039;&gt;Test&lt;/a&gt;

Changelog

VersionChange
8.1.0flags changed from ENT_COMPAT to ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401.

See also

get_html_translation_table(), htmlspecialchars_decode(), strip_tags(), htmlentities(), nl2br()

All PHP 8.5 built-in functions

Reference card built from the PHP manual page htmlspecialchars() (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.