PHP htmlspecialchars_decode() Function: Syntax, Usage Examples, and Precautions
The article explains PHP's htmlspecialchars_decode() function, detailing its syntax, parameters, example code for converting HTML entities back to characters, and important usage considerations such as flags and encoding options for developers in web development.
Syntax of htmlspecialchars_decode() Function
<code>htmlspecialchars_decode(string $string, int $flags = ENT_COMPAT | ENT_HTML401, string|null $encoding = null): string</code>$string : The input string to be converted.
$flags : Optional flags that specify how to convert entities. The default is ENT_COMPAT | ENT_HTML401 , which converts special characters for HTML 4.01.
$encoding : Optional character set used for conversion. By default it uses ini_get("default_charset") , the server's default charset.
Usage Examples
1. Convert HTML Entities
<code>$str = "<h1>Hello, World!</h1>";
$result = htmlspecialchars_decode($str);
echo $result; // Output: <h1>Hello, World!</h1>
</code>In this example we define a string $str that contains HTML entities. By calling htmlspecialchars_decode() we transform those entities back into the corresponding characters and output <h1>Hello, World!</h1> .
2. Specify Conversion Flags and Encoding
<code>$str = "<h1>Hello, World!</h1>";
$result = htmlspecialchars_decode($str, ENT_QUOTES, "UTF-8");
echo $result; // Output: <h1>Hello, World!</h1>
</code>Here we pass $flags as ENT_QUOTES to also convert both double and single quotes, and we set $encoding to UTF-8 . The function returns a new string with the HTML entities decoded.
Precautions
htmlspecialchars_decode() only converts HTML entities; it does not affect other special characters.
If you provide the $flags parameter, the function will follow the specified conversion rules. Common flags include ENT_COMPAT (default), ENT_QUOTES , and ENT_HTML5 .
If you provide the $encoding parameter, the function will use that character set for conversion. Typical encodings are UTF-8 , ISO-8859-1 , etc.
The function returns a new string; the original input string remains unchanged, so you must assign the result to a variable.
Summary
Through this article we learned how to use PHP's htmlspecialchars_decode() function, which performs the reverse operation of htmlspecialchars() by converting HTML entities back to their corresponding special characters. We covered its syntax, demonstrated practical examples, and highlighted important considerations, enabling developers to handle HTML entities more effectively and improve website security and user experience.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.