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

phphtmlspecialchars(string $string, int $flags = ENT_COMPAT, ?string $encoding = null, bool $double_encode = true): string

Example

Let's convert a string with tags:

php<?php
  echo htmlspecialchars('<b>bold text</b>');
?>

Code execution result:

php'<b>text</b>'

Example

Let's convert a string with an ampersand:

php<?php
  $str = 'test: &';
  $res = htmlspecialchars($str);
  
  echo $res;
?>

Code execution result:

php'test: &'

See Also