tags:

views:

50

answers:

1

How can I make a regex pattern for use with the PHP preg_replace function that removes all characters which do not fit in a certain pattern. For example:

[a-zA-Z0-9]
+8  A: 

You can negate the character set by using ^:

[^a-zA-Z0-9]

The ^ only negates the existing character set [...] it is in, and it only applies when it is the first character inside the set. You can read more about negated character sets here

So, finally:

preg_replace('/[^a-zA-Z0-9]/', '', $input);

Edit: As noted in the comments below, you can also add the + quantifier so consecutive invalid characters will be replaced in 1 match of preg_replace's iteration:

preg_replace('/[^a-zA-Z0-9]+/', '', $input);
Matt
you could add quantifier for efficiency.
SilentGhost
@SilentGhost - true, thanks. Edited.
Matt
Thanks for this. All work very nicely!
jSherz