How to Convert Special Characters to HTML Entities - htmlspecialchars() Function
PHP String FunctionsCertain characters have special significance in HTML, and should be represented by HTML entities if they are to preserve their meanings.
Special Characters
This function converts five special characters to their corresponding HTML entities:
- < (less than) - <
- > (greater than) - >
- & (ampersand) - &
- " (double quote) - "
- ' (single quote) - ' or '
Syntax
htmlspecialchars(string $string, int $flags = ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401)
Flags
This specifies how to handle quotes, invalid code unit sequences and the used document type. The default is ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401.
- 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 single quotes unconverted.
Example
$new = htmlspecialchars("<a href='test'>Test</a>", ENT_QUOTES);
echo $new;
Output: <a href='test'>Test</a>
htmlentities() Function
If you require all input substrings that have associated named entities to be translated, use htmlentities() instead. It converts all characters that have HTML character entity equivalents.
htmlspecialchars_decode() Function
This function converts special HTML entities back to characters. This function is the opposite of htmlspecialchars().
The converted entities are: &, " (when ENT_NOQUOTES is not set), ' (when ENT_QUOTES is set), < and >.