PHP htmlspecialchars() | Convert Special Characters to HTML Entities

The PHP htmlspecialchars() function is used when we need to covert some malicious special characters into HTML entities. For example:

<?php
   $x = "&";
   $result = htmlspecialchars($x);
?>

The variable $result now contains &amp;

PHP htmlspecialchars() Syntax

The syntax of htmlspecialchars() function in PHP, is:

htmlspecialchars(string, flags, character-set, double_encode)

Only the first (string) parameter is required. All the other parameters are optional.

Note - The string parameter refers to the string, to convert special characters (if any) available in it into equivalent HTML entities. Here are the list of special characters that will be converted into HTML entities using the htmlspecialchars() function:

  • & converted into &amp;
  • " converted into &quot;
  • ' converted into &#039;
  • < converted into &lt;
  • > converted into &gt;

Note - The flags parameter specifies the way to handle quotes, invalid encoding and used document types. For example:

// To covert only double quotes, use following code
htmlspecialchars(string, ENT_COMPAT);

// To convert both single and double quotes, use following code
echo htmlspecialchars(string, ENT_QUOTES);

// Use following code to do not convert any quotes
echo htmlspecialchars($str, ENT_NOQUOTES);

Note - The character-set parameter is used to specify the character-set to use.

Note - The double_encode parameter is used to specify whether to encode existing HTML entities or not, using boolean value.

PHP Online Test


« Previous Tutorial Next Tutorial »

Like/Share Us on Facebook 😋