Home >>PHP String Functions >PHP htmlspecialchars() Function

PHP htmlspecialchars() Function

PHP htmlspecialchars() Function

PHP htmlspecialchars() function is used to convert all the available pre-defined characters into HTML entities. htmlspecialchars() function is an in-built function of PHP. The pre-defined characters which get converted into HTML entities are:-

  • & (ampersand) get converted into &
  • " (double quote) get converted into "
  • ' (single quote) get converted into '
  • < (less than) get converted into &lt;
  • > (greater than) get converted into &gt;

PHP htmlspecialchars_decode() function is the opposite of PHP htmlspecialchars() function. htmlspecialchars_decode() function is used to convert all the special HTML entities back to the pre-defined characters.

Syntax:-

 String htmlspecialchars ( $string, $flags, $encoding, $double_encode );  

Parameter Values

Parameter Description
string This is a required parameter. This parameter is used to hold the given input string.
flags This is an optional parameter. This parameter is used to hold the flags value. This parameter defines how to handle quotes, invalid encoding and the used document type.
charset This is an optional parameter. This parameter holds a string that defines which character-set to use in the function.
double_encode This is an optional parameter.This parameter holds a boolean value that defines whether to encode existing html entities or not.

Here is an example of htmlspecialchars() function in PHP:

<html>
<body>

<?php
$str = "ME & YOU.";
echo htmlspecialchars($str);
?>

</body>
</html>
Output:
Me &amp; YOU.

Here is an another example of htmlspecialchars() function in PHP:

<html>
<body>

<?php
$str = '"PHP" is best.';
echo htmlspecialchars($str, ENT_QUOTES);
?>

</body>
</html>
Output:
&quot;PHP&quot; is best.

Here is an another example of htmlspecialchars() function in PHP using the $flags parameter:

<html>
<body>

<?php
$str = "Me & 'You'";
echo htmlspecialchars($str, ENT_COMPAT); //Converts double quotes only
echo "<br>";
echo htmlspecialchars($str, ENT_QUOTES); // Converts double and single quotes both
echo "<br>";
echo htmlspecialchars($str, ENT_NOQUOTES); // Does not convert any quotes
?>

</body>
</html>
Output:
Me &amp; 'You'
Me &amp; &#039;You&#039;
Me &amp; 'You'

Popular Tutorials