39
votes

I'd like a regexp or other string which can replace everything except alphanumeric chars (a-z and 0-9) from a string. All things such as ,@#$(@*810 should be stripped. Any ideas?

Edit: I now need this to strip everything but allow dots, so everything but a-z, 1-9, .. Ideas?

5

5 Answers

70
votes
$string = preg_replace("/[^a-z0-9.]+/i", "", $string);

Matches one or more characters not a-z 0-9 [case-insensitive], or "." and replaces with ""

21
votes

I like using [^[:alnum:]] for this, less room for error.

preg_replace('/[^[:alnum:]]/', '', "(ABC)-[123]"); // returns 'ABC123'
2
votes

Try:

$string = preg_replace ('/[^a-z0-9]/i', '', $string);

/i stands for case insensitivity (if you need it, of course).

2
votes
/[^a-z0-9.]/

should do the trick

1
votes

This also works to replace anything not a digit, a word character, or a period with an underscore. Useful for filenames.

$clean = preg_replace('/[^\d\w.]+/', '_', $string);