Ibrahim
Ibrahim

Reputation: 1279

Regex in php - letters and numbers with limited length

How do I make a regex that enforces:

when using a php preg_match?


Here's what I got:

 ^[A-Za-z0-9]{10,50}$

It seems to do everything except enforce letters AND numbers.

Upvotes: 8

Views: 1855

Answers (1)

heemayl
heemayl

Reputation: 41987

Do:

^(?=.*(?:[A-Za-z].*\d|\d.*[A-Za-z]))[A-Za-z0-9]{10,50}$
  • (?=.*(?:[A-Za-z].*\d|\d.*[A-Za-z])) is zero width positive lookahead, this makes sure there is at least one letter, and one digit present

  • [A-Za-z0-9]{10,50} makes sure the match only contains letters and digits

Demo


Or even cleaner, use two lookaheads instead of OR-ing (thanks to chris85):

^(?=.*[A-Za-z])(?=.*\d)[A-Za-z0-9]{10,50}$

Upvotes: 6

Related Questions