Saturday 26 May 2012

Remove Special Characters from a String using preg_replace in Php

Hi All, in my earlier post i have written about how to remove special characters from mysql database. Sometime we only want to get result of an input string as a simple composition of alphabets and numbers and we want to remove all special characters in the given string.
In this case Php provide an easy function to do the needful. We can remove all special characters by using preg_replace.
Here is the simple syntax for it.

$result  = preg_replace('/[^a-zA-z0-9/s','',$string);
where $string is the string in which we want to filter special characters and $result is the output string without any special characters.

We can also use another Php function str_replace() to achieve the same if we know what all we have to remove. Here is the simple syntax for it.
str_replace(mixed search,mixed replace,mixed subject[,int & replace_count]);

More information on www.narendrarathore.com