How to Remove Special Character from String in PHP



In this tutorial I will show you how to remove special character from string in PHP. Sometimes we need to remove all special characters by using preg_replace from input string. There are two option available to remove special character from string using php.

Option 1: Using preg_replace PHP Function

We can remove special character from sting using preg_replace, it’s using regular expression to special character from string.

Syntax of preg_replace PHP Function:

$result = preg_replace($pattern, $replaceWith, $string);
Remove Special Character from String in PHP:
function RemoveSpecialCharacters($string){
	$result  = preg_replace('/[^a-zA-Z0-9_ -]/s','', $string);
	return $result;
}
How to Use above function:
echo RemoveSpecialCharacters("it's working' fine to me' ! wow");

output : its working fine to me wow

Option 2: Using str_replace PHP Function

You can also use PHP function str_replace() to get the same result as above script, if we know what all we have to remove special characters.

Syntax of str_replace PHP Function:

$result = str_replace( array( '\'', '"', ',' , ';', '<', '>', '!' ), ' ', $string);

Example to Remove Special Character from String in PHP:

function RemoveSpecialCharacters($string){
	$result = str_replace( array( '\'', '"', ',' , ';', '<', '>', '!' ), ' ', $string);
	
	return $result;
}
How to Use above function:
echo RemoveSpecialChar("it's working' fine to me' ! wow");

output : it s working fine to me wow