How to Convert Special HTML Entities Back to Characters in PHP?
Last Updated :
24 Apr, 2024
Sometimes, when we work with HTML in PHP, you may encounter special characters that are represented using HTML entities. These entities start with an ampersand (&) and end with a semicolon (;). For example, < represents <, > represents >, and & represents &. To convert these HTML entities back to their original characters, you can use PHP’s built-in functions such as html_entity_decode() and htmlspecialchars_decode(). In this article, we will explore both approaches with explanations and code examples.
Approach 1: Convert HTML Entities to Characters using html_entity_decode() Function
The html_entity_decode() function converts HTML entities to their corresponding characters. It takes an optional second parameter $flags to specify how to handle quotes and which character set to use.
PHP
<?php
$htmlEntities = "<h1>Welcome to GeeksforGeeks</h1>";
$decodedStr = html_entity_decode($htmlEntities);
echo $decodedStr;
?>
Output<h1>Welcome to GeeksforGeeks</h1>
Approach 2: Convert HTML Entities to Characters using htmlspecialchars_decode() Function
The htmlspecialchars_decode() function converts special HTML entities back to characters. It is useful when dealing with encoded strings that were created using htmlspecialchars().
PHP
<?php
$htmlEntities = "<h1>Welcome to GeeksforGeeks</h1>";
$decodedStr = htmlspecialchars_decode($htmlEntities);
echo $decodedStr;
?>
Output<h1>Welcome to GeeksforGeeks</h1>
Share your thoughts in the comments
Please Login to comment...