The following simple code samples will use PHP regular expressions strip away all characters from a string that are not letters or number.

In another code snippet I added today, I showed how to strip away every character but numbers.

This is a little more complicated because not everyone wants the same things. Some people want nothing left but letters and numbers, some people want to leave spaces, and others want to be able to have dashes and apostrophes (that might appear in people’s names). I’ll show you all of those examples below, so it can help more people.

The following snippets are perfect for PHP 5.3.

leave- letters, numbers

$str = preg_replace("/[^A-Za-z0-9]/","",$str);

leave- letters, numbers, spaces

/* 3 choices. Pick one you like! */
$str = preg_replace("/[^A-Za-z0-9 ]/","",$str);
$str = preg_replace("/[^A-Za-z0-9\s]/","",$str);
$str = preg_replace("/[^A-Za-z0-9[:space:]]/","",$str);

leave- letters, numbers, dashes, apostrophes

$str = preg_replace("/[^A-Za-z0-9'-]/","",$str);

leave- letters, numbers, dashes, apostrophes, spaces

$str = preg_replace("/[^A-Za-z0-9' -]/","",$str);

If you have any more common string scenarios that you think are worthy of being in this list, leave a comment!