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]
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With