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<?phphtmlentities(string $string, int $flags = ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401, ?string $encoding = null, bool $double_encode = true): string?>
Parameters1. `$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, <b>World</b> & 'PHP'!
Example 2: Prevent Double Encoding
<?php$str = "Tom & Jerry & Friends";echo htmlentities($str, ENT_QUOTES, "UTF-8", false);?>
Output:Tom & Jerry & Friends
Example 3: Handling Different Quote Options
<?php$str = "\"Hello\" 'PHP'!";echo htmlentities($str, ENT_NOQUOTES); // Does not convert quotesecho "<br>";echo htmlentities($str, ENT_QUOTES); // Converts both single & double quotes?>
Output:"Hello" 'PHP'! (With ENT_NOQUOTES)"Hello" 'PHP'! (With ENT_QUOTES)
Example 4: Using Different Encoding Types
<?php$str = "Caf & Dj Vu";echo htmlentities($str, ENT_QUOTES, "ISO-8859-1");?>
Output:Café & Déjà Vu