The htmlspecialchars Function
The htmlspecialchars function allows
you to output tags to the browser so that it does not consider
them commands, but outputs them as strings. The function
converts the ampersand & to &,
the less-than sign < to <, the greater-than sign
> to >.
If you need to convert all
possible HTML entities, use htmlentities.
Syntax
htmlspecialchars(string $string, int $flags = ENT_COMPAT, ?string $encoding = null, bool $double_encode = true): string
Example
Let's convert a string with tags:
<?php
echo htmlspecialchars('<b>bold text</b>');
?>
Code execution result:
'<b>text</b>'
Example
Let's convert a string with an ampersand:
<?php
$str = 'test: &';
$res = htmlspecialchars($str);
echo $res;
?>
Code execution result:
'test: &'
See Also
-
the
htmlspecialchars_decodefunction,
which performs the reverse operation -
the
htmlentitiesfunction,
which performs a similar operation -
the
strip_tagsfunction,
which removes tags from a string