Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex Entire Input Matches Pattern

Tags:

regex

php

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]
like image 363
jSherz Avatar asked Feb 04 '26 18:02

jSherz


1 Answers

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);
like image 71
Matt Avatar answered Feb 07 '26 17:02

Matt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!