PHP htmlentities() Function: Usage, Parameters, and Examples
This article explains PHP's htmlentities() function, detailing its signature, parameters, flag options, return behavior, and provides multiple code examples demonstrating how to convert characters to HTML entities and handle encoding nuances.
The htmlentities() function in PHP converts characters to their corresponding HTML entity representations, similar to htmlspecialchars() but covering all characters that have HTML entities.
Signature: string htmlentities(string $string, int $flags = ENT_COMPAT|ENT_HTML401, string $encoding = ini_get("default_charset"), bool $double_encode = true)
Parameters:
string : the input string.
flags (optional): determines how quotes, invalid code units, and document type are handled. Common flags include ENT_COMPAT (default, encodes double quotes), ENT_QUOTES (encodes both single and double quotes), ENT_NOQUOTES (no quotes), as well as ENT_IGNORE , ENT_SUBSTITUTE , ENT_DISALLOWED for invalid encoding handling, and document type flags such as ENT_HTML401 , ENT_HTML5 , ENT_XML1 , ENT_XHTML .
encoding (optional): character set used for conversion, default is the value of default_charset .
double_encode (optional): whether to convert existing HTML entities; default true .
Return value: the encoded string, or an empty string if the input contains invalid code units and neither ENT_IGNORE nor ENT_SUBSTITUTE is set.
Examples:
<?php
$str = "A 'quote' is
bold
";
echo htmlentities($str); // A 'quote' is <b>bold</b>
echo htmlentities($str, ENT_QUOTES); // A 'quote' is <b>bold</b>
?>Handling invalid encoding:
<?php
$str = "\x8F!!!";
echo htmlentities($str, ENT_QUOTES, "UTF-8"); // (empty string)
echo htmlentities($str, ENT_QUOTES|ENT_IGNORE, "UTF-8"); // !!!
?>Controlling which quotes are encoded:
<?php
$str = "Bill & 'Steve'";
echo htmlentities($str, ENT_COMPAT); // Only double quotes encoded
echo htmlentities($str, ENT_QUOTES); // Both single and double quotes encoded
echo htmlentities($str, ENT_NOQUOTES); // No quotes encoded
?>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.