+2 votes
in Programming Languages by (71.8k 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

+2 votes
by (56.8k points)
selected by
 
Best answer

You can use regular expression to get the desired result.

Example

$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.


...