PHP htmlspecialchars Function: Description, Parameters, Return Value, and Usage Examples
This article explains the PHP htmlspecialchars function, detailing its purpose of converting predefined characters to HTML entities, describing each parameter and return value, and providing multiple code examples that demonstrate different flag options and their effects on output.
The htmlspecialchars function converts predefined characters such as <, >, &, " and ' into their corresponding HTML entities, helping to prevent XSS attacks and ensuring proper HTML rendering.
Function signature :
string htmlspecialchars ( string $string [, int $flags = ENT_COMPAT|ENT_HTML401 [, string $encoding = ini_get("default_charset") [, bool $double_encode = true ]]] )
Parameters :
string $string (required) – the input string to be converted.
int $flags (optional) – determines how quotes and invalid code points are handled; common values are ENT_COMPAT , ENT_QUOTES , ENT_NOQUOTES , and document type flags like ENT_HTML401 .
string $encoding (optional) – character set to use, defaulting to the value of default_charset .
bool $double_encode (optional) – if true , existing HTML entities are encoded again; set to false to leave them untouched.
Return value :
The function returns the converted string. If the input contains invalid encoding, an empty string is returned unless ENT_IGNORE or ENT_SUBSTITUTE flags are set.
Example 1 – Different flag options :
<?php
$str = "Bill & 'Steve'";
// Convert only double quotes (default behavior)
echo htmlspecialchars($str, ENT_COMPAT);
// Convert both double and single quotes
echo htmlspecialchars($str, ENT_QUOTES);
// Do not convert any quotes
echo htmlspecialchars($str, ENT_NOQUOTES);
?>Output of the above code:
Bill & 'Steve'<br>
Bill & 'Steve'<br>
Bill & 'Steve'Example 2 – Converting quotes inside a string :
<?php
$str = 'I love "PHP".';
echo htmlspecialchars($str, ENT_QUOTES);
?>Result:
I love "PHP".Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
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.