PHP

How to Remove Special Characters From String in PHP


In this article, you will learn how to remove special characters from a string in PHP.

Let’s say you have a string variable named ‘a’.

// A string variable named 'a' with value "This string, contains special characters such as <;>"
$a = "This string, contains special characters such as <;>";

Remove Special Characters From String

In order to remove special characters from a string, you can use the str_replace() method.

// A string variable named 'a' with value "This string, contains special characters such as <;>"
$a = "This string, contains special characters such as <;>";

// Replace any special characters in string to whitespace
$result = str_replace(array( '"', ',' , ';', '<', '>' ), ' ', $a); 

echo "Result: ".$result;
// Result: This string contains special characters such as

Note: The str_replace() method functions by removing all special characters from the supplied string by replacing them with whitespaces.


Share on social media

//