Signup/Sign In
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 &amp

  • " (double quote) will be converted to &quot

  • ' (single quote) will be converted to &#039

  • < (less than) will be converted to &lt

  • > (greater than) will be converted to &gt

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

PHP

Output on the Source

PHP_so

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

special_char

On the Source

special_char

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.



About the author:
I am the founder of Studytonight. I like writing content about C/C++, DBMS, Java, Docker, general How-tos, Linux, PHP, Java, Go lang, Cloud, and Web development. I have 10 years of diverse experience in software development.