PHP htmlspecialchars () function
Examples
The predefined characters "<" (less than) and ">" (greater than) converted to HTML entities:
$str = "This is some <b>bold</b> text.";
echo htmlspecialchars($str);
?>
HTML output of the code above is as follows (view source):
<html>
<body>
This is some <b>bold</b> text.
</body>
</html>
Browser output of the code above is as follows:
Running instance »
Definition and Usage
htmlspecialchars () function to some predefined characters into HTML entities.
The predefined characters are:
- & (Ampersand) becomes & amp;
- "(Double quote) becomes & quot;
- '(Single quote) becomes'
- <(Less than) becomes & lt;
- > (Greater than) becomes & gt;
Tip: To get special HTML entities back to character, use htmlspecialchars_decode () function.
grammar
parameter | description |
---|---|
string | Required. Provisions of string to be converted. |
flags | Optional. How to deal with the provisions of the quotes, invalid encoding and which document types. Available types of quotes:
Invalid code:
Document types require the use of additional flags:
|
character-set | Optional. A string that specifies the character set to be used. Allowed values:
Note: In the previous version 5.4 PHP, can not be recognized set of characters will be ignored by the ISO-8859-1 instead.Since PHP 5.4 onwards, the character set can not be identified will be ignored by the UTF-8 instead. |
double_encode | Optional. A Boolean value that specifies whether the encoding existing HTML entities.
|
technical details
return value: | Returns the converted string. If the string contains invalid code, an empty string is returned, unless the ENT_IGNORE or ENT_SUBSTITUTE flag. |
---|---|
PHP version: | 4+ |
Update log: | In PHP 5, default value character-set parameters to UTF-8. In PHP 5.4, and added: ENT_SUBSTITUTE, ENT_DISALLOWED, ENT_HTML401, ENT_HTML5, ENT_XML1 and ENT_XHTML. In PHP 5.3, add the ENT_IGNORE. In PHP 5.2.3, add the double_encode parameters. In PHP 4.1, add the character-set parameters. |
More examples
Example 1
Some predefined characters into HTML entities:
$str = "Jane & 'Tarzan'";
echo htmlspecialchars($str, ENT_COMPAT); // Will only convert double quotes
echo "<br>";
echo htmlspecialchars($str, ENT_QUOTES); // Converts double and single quotes
echo "<br>";
echo htmlspecialchars($str, ENT_NOQUOTES); // Does not convert any quotes
?>
HTML output of the code above is as follows (view source):
<html>
<body>
Jane & 'Tarzan'<br>
Jane & 'Tarzan'<br>
Jane & 'Tarzan'
</body>
</html>
Browser output of the code above is as follows:
Jane & 'Tarzan'
Jane & 'Tarzan'
Running instance »
Example 2
The double quotes into HTML entities:
$str = 'I love "PHP".';
echo htmlspecialchars($str, ENT_QUOTES); // Converts double and single quotes
?>
HTML output of the code above is as follows (view source):
<html>
<body>
I love "PHP".
</body>
</html>
Browser output of the code above is as follows:
Running instance »
PHP String Reference