PHP htmlspecialchars() Function

PHP htmlspecialchars() Function

The htmlspecialchars() function in PHP converts some special predefined characters to HTML entities.

The special predefined characters are as follows:

  • & (ampersand) OR &
  • " (double quote) OR "
  • ' (single quote) OR '
  • < (less than) OR &lt;
  • (greater than) OR &gt;

Syntax

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

Parameter

string(required)- This parameter specifies the string to convert.

flags(optional)- This parameter specifies how to handle quotes, invalid encoding and the used document type. The available flag constants are as follows:

  • ENT_COMPAT- Table contains entities only for double-quotes
  • ENT_QUOTES- The Table contains entities for both double and single quotes
  • ENT_NOQUOTES- Table contains entities neither for single quotes nor for double quotes.
  • ENT_HTML401- Table specifically for HTML 4.01.
  • ENT_XML1- Table for XML 1.
  • ENT_XHTML- Table for XHTML.
  • ENT_HTML5- Table for HTML 5.

double_encode(optional)- It represents a boolean value that specifies whether to encode existing html entities or not.

character-set(optional)-This parameter represents a string that specifies which character-set to use.

Return

This method returns the converted string.

Example 1

<?php
 // initializing the string
 $str = "<Tutorial>&<Example>";
 echo htmlspecialchars($str, ENT_COMPAT); // Will only convert double quotes
 echo "\n";
 echo htmlspecialchars($str, ENT_QUOTES); // will convert the double and single quotes 
 echo "\n";
 echo htmlspecialchars($str, ENT_NOQUOTES); // Does not convert any quotes
 ?> 

Output

<Tutorial>&<Example>
 <Tutorial>&<Example>
 <Tutorial>&<Example> 

Example 2

<?php
    $str = htmlspecialchars("<a href='Hello World'>Hello World</a>", ENT_QUOTES);
    echo $str;
 ?> 

Output

<a href='tutorialspoint'>Tutorialspoint</a>

Example 3

<?php
 $str = '"PHP" is easy to learn.';
 echo htmlspecialchars($str, ENT_QUOTES); // Converting only the double and single quotes
 ?> 

Output

"PHP" is easy to learn.