Remove all special characters from a string

phptutorial

You want to be able to convert strings that could contain anything and have them stripped of all special characters so they only have letters and numbers and of course you would like to replace spaces with hyphens.

This should do what you're looking for:

function clean($string) {
   $string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.

   return preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.
}

Usage:

echo clean('a|"bc!@£de^&$f g');

Will output: abcdef-g

 

(0)
FREE
Developer Information
Submitted by ALIKOBOND
RUE VGE, Koumassi,
00225 09900500