In this tutorial I will discuss how to remove special character from string in PHP. Sometimes we need to get result of an input string as a simple composition of alphabets and numbers and we want to remove all special characters by using preg_replace.
Here is the simple syntax:
$result = preg_replace($pattern, $replaceWith , $string);
$result = This is the output string without special characters.
$string = This is the string which you want filter special characters.
Code:
1 2 3 4 5 6 7 8 9
function RemoveSpecialChar($value){
$result = preg_replace('/[^a-zA-Z0-9_ -]/s','',$value);
return $result;
}
How to Call method:
echo $obj->RemoveSpecialChar(“does’t happened ‘ ‘ test”);
Result:
does t happened test
You can also use another PHP function str_replace() to get the same result as above script, if we know what all we have to remove special characters.
The syntax is:
$title = str_replace( array( ‘\”, ‘”‘, ‘,’ , ‘;’, ‘<', '>‘ ), ‘ ‘, $value);
Example:
Code
function RemoveSpecialChar($value){
$title = str_replace( array( ‘\”, ‘”‘, ‘,’ , ‘;’, ‘<', '>‘ ), ‘ ‘, $value);
return $title;
}
How to call Method
echo $obj->RemoveSpecialChar(“does’t happened ‘ ‘ test”);
Result:
does t happened test