Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

htmlentities() vs htmlspecialchars() Function in PHP

  • Last Updated : 21 Aug, 2019

htmlentities() Function

The htmlentities() function is an inbuilt function in PHP which is used to transform all characters which are applicable to HTML entities. This function converts all characters that are applicable to HTML entity.

Syntax

string htmlentities( $string, $flags, $encoding, $double_encode )

Parameters: This function accepts four parameters as mentioned above and described below:

  • $string: This parameter is used to hold the input string.
  • $flags: This parameter is used to hold the flags. It is combination of one or two flags, which tells how to handle quotes.
  • $encoding: It is an optional argument which specifies the encoding which is used when characters are converted. If encoding is not given then it is converted according to PHP default version.
  • $double_encode: If double_encode is turned off then PHP will not encode existing HTML entities. The default is to convert everything.

Return Values: This function returns the string which has been encoded.



Example:




<?php
  
// String convertable to htmlentities 
$str = '<a href="https://www.geeksforgeeks.org">GeeksforGeeks</a>';
  
// It will convert htmlentities and print them
echo htmlentities( $str );
?>
Output:
&lt;a href=&quot;https://www.geeksforgeeks.org&quot;&gt;GeeksforGeeks&lt;/a&gt;

htmlspecialchars() Function

The htmlspecialchars() function is an inbuilt function in PHP which is used to convert all predefined characters to HTML entities.

Syntax:

string htmlspecialchars( $string, $flags, $encoding, $double_encode )
  • $string: This parameter is used to hold the input string.
  • $flags: This parameter is used to hold the flags. It is combination of one or two flags, which tells how to handle quotes.
  • $encoding: It is an optional argument which specifies the encoding which is used when characters are converted. If encoding is not given then it is converted according to PHP default version.
  • $double_encode: If double_encode is turned off then PHP will not encode existing HTML entities. The default is to convert everything.

Return Values: This function returns the converted string. If there is invalid input string then empty string will returned.

Example:




<?php
  
// Example of htmlspecialchars() function
  
// String to be converted
$str = '"geeksforgeeks.org" Go to GeeksforGeeks';
  
// Converts double and single quotes
echo htmlspecialchars($str, ENT_QUOTES); 
?>
Output:
&quot;geeksforgeeks.org&quot; Go to GeeksforGeeks

Difference between htmlentities() and htmlspecialchars() function: The only difference between these function is:

  • htmlspecialchars() function convert the special characters to HTML entities.
  • htmlentities() function convert all applicable characters to HTML entities.



My Personal Notes arrow_drop_up
Recommended Articles
Page :