htmlentities() Function in PHP 8.5

htmlentities() in PHP 8.5 converts all characters that have HTML character entity equivalents into those entities. It is almost identical to htmlspecialchars(), but it encodes a wider range of characters .

Function Signature

htmlentities(
   string $string,
   int $flags = ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401,
   ?string $encoding = null,
   bool $double_encode = true
): string

Key Parameters

→$string: The input string to be converted.
→$flags: Controls how quotes are handled and which document type is used. The default converts both single and double quotes. You can use ENT_HTML5 for HTML5 entities .
→$encoding: Specifies the character encoding. It defaults to the default_charset configuration, but explicitly setting it to "UTF-8" is highly recommended for modern applications .
→$double_encode: When set to false, existing HTML entities will not be encoded again .

Example

<?php
$string = "Hello <b>World</b> & Friends ";

// Default behavior (ENT_QUOTES | ENT_HTML401)
echo htmlentities($string);
// Output: Hello &lt;b&gt;World&lt;/b&gt; &amp; &#039;Friends&#039;

// Using HTML5 rules with UTF-8 encoding
echo htmlentities($string, ENT_QUOTES | ENT_HTML5, "UTF-8");
// Output: Hello &lt;b&gt;World&lt;/b&gt; &amp; &apos;Friends&apos;
?>

Summary

Use htmlentities() when you need to convert all applicable characters (not just special HTML characters) to entities. For basic HTML escaping, htmlspecialchars() is usually sufficient and faster. To reverse the process, use html_entity_decode().

9 Views