Regular expression in php letters and limited length numbers

How to create a regular expression that provides:

  • letters and numbers (at least 1)
  • minimum and maximum length (10 to 50)
  • nothing but letters or numbers

when using php preg_match?


Here is what I got:

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

Everything seems to do everything except force input of letters AND numbers.

+7
php regex preg-match
source share
1 answer

do:

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

  • [A-Za-z0-9]{10,50} ensures that the match contains only letters and numbers

Demo


Or even cleaner, use two kinds instead of two ORGING (thanks to chris85 ):

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

All Articles