Friday, August 26, 2011

Remove special characters - PHP


Hi,

I know there are a million ways to remove special characters but this is one of the better solutions which I came across over the internet. Here is the PHP function:

function just_clean($string)
{
// Replace other special chars
$specialCharacters = array(
‘#’ => ”,
‘$’ => ”,
‘%’ => ”,
‘&’ => ”,
‘@’ => ”,
‘.’ => ”,
‘€’ => ”,
‘+’ => ”,
‘=’ => ”,
‘§’ => ”,
‘\\’ => ”,
‘/’ => ”,
);
while (list($character, $replacement) = each($specialCharacters)) {
$string = str_replace($character, '-' . $replacement . '-', $string);
}
$string = strtr($string,
"ÀÁÂÃÄÅ? áâãäåÒÓÔÕÖØòóôõöøÈÉÊËèéêëÇçÌÍÎÏìíîïÙÚÛÜùúûüÿÑñ",
"AAAAAAaaaaaaOOOOOOooooooEEEEeeeeCcIIIIiiiiUUUUuuuuyNn"
);
// Remove all remaining other unknown characters
$string = preg_replace('/[^a-zA-Z0-9\-]/', ' ', $string);
$string = preg_replace('/^[\-]+/', '', $string);
$string = preg_replace('/[\-]+$/', '', $string);
$string = preg_replace('/[\-]{2,}/', ' ', $string);
return $string;
}

Best of luck

1 comment:

  1. Thanks a lot. I got many codes. But most of them showed some limitations somwhere. This works better. Thank you :)

    ReplyDelete