Jen Gerfeld
Jen Gerfeld

Reputation: 33

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?

Upvotes: 2

Views: 1799

Answers (7)

Kristoffer Sall-Storgaard
Kristoffer Sall-Storgaard

Reputation: 10636

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).

Upvotes: 2

codaddict
codaddict

Reputation: 454920

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.

Upvotes: 9

Jojo Sardez
Jojo Sardez

Reputation: 8558

Try

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

Upvotes: 0

dale
dale

Reputation: 758

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

Upvotes: 0

Dominic Rodger
Dominic Rodger

Reputation: 99751

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

Your current code actually does allow both A-Z and a-z - the i flag marks your regular expression as case-insensitive.

Upvotes: 1

a'r
a'r

Reputation: 36989

If you know exactly what you need to match, just specify it in a character group. The dash either needs to be at the very start or very end.

/[A-Z0-9._-]/

Upvotes: 1

Kobi
Kobi

Reputation: 137997

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

Removes anything that isn't ([^]) one of the characters on the group. Note the hypern is the last one there, so it loses its special meaning.

Upvotes: 1

Related Questions