How to remove non-alphanumeric characters?


Question

I need to remove all characters from a string which aren't in a-z A-Z 0-9 set or are not spaces.

Does anyone have a function to do this?

1
321
3/19/2015 7:33:25 PM

Accepted Answer

Sounds like you almost knew what you wanted to do already, you basically defined it as a regex.

preg_replace("/[^A-Za-z0-9 ]/", '', $string);
652
8/23/2017 10:28:16 PM

For unicode characters, it is :

preg_replace("/[^[:alnum:][:space:]]/u", '', $string);

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon