108 of 410 menu

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 &amp;, the less-than sign < to &lt;, the greater-than sign > to &gt;.

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

byenru