Home >>PHP String Functions >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:-
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 | 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>
Here is an another example of htmlspecialchars() function in PHP:
<html> <body> <?php $str = '"PHP" is best.'; echo htmlspecialchars($str, ENT_QUOTES); ?> </body> </html>
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>