+2 votes
in Programming Languages by (18.6k points)
edited by
I have strings which can have non-alphanumeric characters. I want to remove them all so that the resulting string will have only alphanumeric characters. How can I do that?

1 Answer

0 votes
by (15.4k points)

You can use regular expression to get the desired result.


$str = preg_replace('/[^a-z\d ]/i', '', $str);

The i stands for case insensitive. ^ means, does not start with. \d matches any digit. a-z matches all characters between a and z. Because of the i parameter you don't have to specify a-z and A-Z. After \d there is a space, so spaces are allows in this regex.