In PHP 8.3 & PHP 8.4, the `html_entity_decode()` function is used to convert HTML entities back to their corresponding characters. This is useful when you have a string containing HTML entities (e.g., `&`, `<`, `>`, etc.) and you want to decode them into their original characters.
Syntax:
<?php html_entity_decode(string $string, int $flags = ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401, ?string $encoding = null): string ?>
Parameters:
1. `$string`: The input string containing HTML entities.
2. `$flags`: (Optional) A bitmask of flags to control how the function behaves. Common flags include:
– `ENT_COMPAT`: Decodes double quotes (`”`) but not single quotes (`’`).
– `ENT_QUOTES`: Decodes both double and single quotes.
– `ENT_NOQUOTES`: Does not decode any quotes.
– `ENT_SUBSTITUTE`: Replaces invalid code unit sequences with a Unicode replacement character.
– `ENT_HTML401`: Treats the input as HTML 4.01.
3. `$encoding`: (Optional) The character encoding to use (e.g., `UTF-8`). If `null`, the default encoding is used.
Return Value:
The function returns the decoded string.
Example Usage in PHP 8.3 & PHP 8.4:
<?php // Input string with HTML entities $string = "This is a <strong>test</strong> string with & and "quotes"."; // Decode HTML entities $decodedString = html_entity_decode($string); // Output the decoded string echo $decodedString; ?>
Output:
This is a <strong>test</strong> string with & and "quotes".
Example with Custom Flags and Encoding:
<?php // Input string with HTML entities $string = "This is a <strong>test</strong> string with & and "quotes"."; // Decode HTML entities with specific flags and encoding $decodedString = html_entity_decode($string, ENT_QUOTES | ENT_HTML401, 'UTF-8'); // Output the decoded string echo $decodedString; ?>
Output:
This is a <strong>test</strong> string with & and "quotes".
Points:
1. Common Use Case: Decoding HTML entities in strings retrieved from databases or user input.
2. Encoding: Always specify the correct encoding (e.g., `UTF-8`) to ensure proper decoding.
This function is particularly useful when working with web content or sanitized data that contains HTML entities.