Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for alphanumeric

I've this PHP regular expression:

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

It allows only A-Z and 0-9. How can I allow ., - and _ as well?

like image 310
Jen Gerfeld Avatar asked Dec 30 '25 19:12

Jen Gerfeld


2 Answers

You can use the following regex:

/[^a-z0-9._-]/i
  • i at the end is to make the pattern matching case-insensitive. You can drop it and use: /[^a-zA-Z0-9._-]/
  • -(hyphen) has a special meaning in char class if its surrounded on both sided so we put it at the end so that its treated literally. You can also do: /[^a-z0-9.\-_]/ where we are escaping the hyphen
  • A dot in a char class is not a meta char hence will be treated literally and need not be escaped.
like image 59
codaddict Avatar answered Jan 01 '26 09:01

codaddict


Easy, just add those characters to the regular expression as well

$username = preg_replace('/[^a-zA-Z0-9._-]/','',$username)

The . needs to be escaped because its the 'matchall' character, the - goes in the end because otherwise it would be used to define a range (we could ofcourse have just escaped it).

like image 35
Kristoffer Sall-Storgaard Avatar answered Jan 01 '26 07:01

Kristoffer Sall-Storgaard



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!