PHP htmlspecialchars(): Convert Special Characters to HTML Entities

We use the PHP htmlspecialchars() function when we need to change some special characters that could be used to do harm into HTML entities. For example:

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

The variable $result now contains &amp;

PHP htmlspecialchars() Syntax

The syntax of the 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 is the list of special characters that will be converted into HTML entities using the htmlspecialchars() function:

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

// To convert only double quotes, use the following code:
htmlspecialchars(string, ENT_COMPAT);

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

// Use the following code to 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 a boolean value.

Advantages of the htmlspecialchars() function in PHP

Disadvantages of the htmlspecialchars() function in PHP

PHP Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!