htmlentities() String Function Using PHP 8.4

The `htmlentities()` string function in PHP 8.4 is used to convert special characters into HTML entities, preventing security issues like cross-site scripting (XSS) and ensuring proper rendering of text in HTML.

Syntax

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

Parameters

1. `$string` – The input string to convert.
2. `$flags` (optional) – Determines how to handle quotes and invalid characters:
– `ENT_QUOTES` → Converts both single (`’`) and double (`”`) quotes.
– `ENT_NOQUOTES` → Does not convert any quotes.
– `ENT_HTML401`, `ENT_XML1`, `ENT_XHTML`, `ENT_HTML5` → Defines the document type.
3. `$encoding` (optional) – Character encoding (e.g., `UTF-8`, `ISO-8859-1`).
4. `$double_encode` (optional) – If `false`, prevents double encoding of existing entities.

Example 1: Basic Usage

<?php
$str = "Hello, <b>World</b> & 'PHP'!";
echo htmlentities($str);
?>

Output:-

Hello, &lt;b&gt;World&lt;/b&gt; &amp; &#039;PHP&#039;!

Example 2: Prevent Double Encoding

<?php
$str = "Tom & Jerry &amp; Friends";
echo htmlentities($str, ENT_QUOTES, "UTF-8", false);
?>

Output:

Tom & Jerry &amp; Friends

Example 3: Handling Different Quote Options

<?php
$str = "\"Hello\" 'PHP'!";
echo htmlentities($str, ENT_NOQUOTES); // Does not convert quotes
echo "<br>";
echo htmlentities($str, ENT_QUOTES); // Converts both single & double quotes
?>

Output:

"Hello" 'PHP'! (With ENT_NOQUOTES)
&quot;Hello&quot; &#039;PHP&#039;! (With ENT_QUOTES)

Example 4: Using Different Encoding Types

<?php
$str = "Café & Déjà Vu";
echo htmlentities($str, ENT_QUOTES, "ISO-8859-1");
?>

Output:

Caf&eacute; &amp; D&eacute;j&agrave; Vu