CancelImage Upload

How to remove all non alphanumeric characters from a string with Regular Expressions

If you have a string that can only contains alphanumeric values, it is a lot simpler to state the type of characters that are allowed, instead of looking up every possible symbol on the planet and banning it.

Here then is a regular expression that will remove every none-alphanumeric character. The [^ indicates that this is a negative regular expression, the a-zA-Z0-9 allows any kind of regular expression, the \s represents whitespaces, and there you go basically. Use this correctly and you are well on your way to removing all unwanted characters!


$string = "Let's %&/( do some $ string cleaning: @o@#k?? -_";

$string = preg_replace('/[^a-zA-Z0-9\s]+/', '', $string);

echo $string;


The result:

Lets do some string cleaning ok

Want to leave a comment?

No problem. Just enter your email and password below.

register | home | reminder

myDesignTool Networking •