Removing special Characters from string

user1765876 picture user1765876 · Oct 22, 2013 · Viewed 86.8k times · Source

I am using a function for removing special character from strings.

function clean($string) {
   $string = str_replace('', '-', $string); // Replaces all spaces with hyphens.
   return preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.
}

And here is the test case

echo clean('a|"bc!@£de^&$f g');
Will output: abcdef-g

with Reference from SO Answer. The problem is what if ' is the last character in my string , Like I get a string America' from a excel file ,If I put that in this function, it wouldn't escape ' .Any help when first and last character is '

Answer

user2092317 picture user2092317 · Oct 22, 2013

try to replace the regular expectation change

preg_replace('/[^A-Za-z0-9\-]/', '', $string);

with

preg_replace("/[^A-Za-z0-9\-\']/", '', $string);  // escape apostraphe

or

you can str_replace It is quicker and easier than preg_replace() Because it does not use regular expressions.

$text = str_replace("'", '', $string);