PUBLISHED ON: AUGUST 7, 2021
How to remove HTML special characters from a string in PHP?
Answer: Using htmlspecialchars()
function
We can remove the HTML special characters from the string using the PHP htmlspecialchars()
function. This function converts the HTML special characters within the string into HTML entities. Some most used special characters are:
-
& (ampersand) will be converted to &
-
" (double quote) will be converted to "
-
' (single quote) will be converted to '
-
< (less than) will be converted to <
-
> (greater than) will be converted to >
Example: Converting HTML special characters to HTML entities
In the given example, we have removed the special characters from the string using the htmlspecialchars()
function.
<!DOCTYPE html>
<html>
<head>
<title>Split a string into an array</title>
</head>
<body>
<?php
$my_str = "Welcome <b> to </b> Studytonight";
$new_str = htmlspecialchars($my_str);
echo $new_str;
?>
</body>
</html>
Output
Output on the browser
Output on the Source
Using htmlentities()
function
We can also remove the HTML special characters from a string in PHP using the htmlentities()
function. The htmlentities()
function converts the special characters to HTML entities.
Example: Removing special characters from the string
In the given example, we have removed the special characters from the string using htmlentities()
function.
<!DOCTYPE html>
<html>
<head>
<title>Remove HTML special characters from a string</title>
</head>
<body>
<?php
$string = "Hello World! <b>Welcome</b> to Studytonight";
$new_str = htmlentities($string);
echo $new_str;
?>
</body>
</html>
Output
On the browser
On the Source
Conclusion
In this lesson, we have learned how to remove special characters from the string in PHP. Here we have followed two approaches. Firstly, we have used the htmlspacialchars()
function to remove the special characters from the string. Then we have used the htmlentities()
function to remove the special characters from the given string.