In this article, we will see what htmlentities() & htmlspecialchars() Function is used for & also understand their implementation through the examples.
htmlentities() Function: The htmlentities() function is an inbuilt function in PHP that is used to transform all characters which are applicable to HTML entities. This function converts all characters that are applicable to HTML entities.
Syntax:
string htmlentities( $string, $flags, $encoding, $double_encode )
Parameters value: 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 a combination of one or two flags, which tells how to handle quotes.
- $encoding: It is an optional argument that specifies the encoding which is used when characters are converted. If encoding is not given then it is converted according to the 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: This example uses the htmlentities() function to transform all characters which are applicable to HTML entities.
PHP
<?php // String convertible to htmlentities // It will convert htmlentities and print them echo htmlentities( $str ); ?> |
Output:
<a href="https://www.geeksforgeeks.org">neveropen</a>
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 )
Parameter value:
- $string: This parameter is used to hold the input string.
- $flags: This parameter is used to hold the flags. It is a combination of one or two flags, which tells how to handle quotes.
- $encoding: It is an optional argument that specifies the encoding which is used when characters are converted. If encoding is not given then it is converted according to the 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 an invalid input string then an empty string will be returned.
Example: This example uses the htmlspecialchars() function to convert all predefined characters to HTML entities.
PHP
<?php // String to be converted $str = '"geeksforgeeks.org" Go to neveropen' ; // Converts double and single quotes echo htmlspecialchars( $str , ENT_QUOTES); ?> |
Output:
"geeksforgeeks.org" Go to neveropen
Difference between htmlentities() and htmlspecialchars() function: The only difference between these function is that htmlspecialchars() function convert the special characters to HTML entities whereas htmlentities() function convert all applicable characters to HTML entities.