How to Strip Non-Alphanumeric Characters From a String with PHP

Last updated: October 27, 2009

There are often times when non-alphanumeric characters in a string can be troublesome. For example, if you are using a string in order to name a file, you would want to eliminate any characters that are illegal in a filename. The following two commands (you can nest them, if you want) will first strip out all the characters except spaces, then convert the spaces to hyphens (or you can use underscores, etc.). Use only the first, if you wish to keep the spaces.

$my_new_string = preg_replace("/[^a-zA-Z0-9\s]/", "", $original_string);

$my_new_string = str_replace(" ","-",$my_new_string);