Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: preg_match length limit

I use preg_match('/[a-z]+[0-9]/', strtolower($_POST['value'])) for check that the string contains both letters and numbers. How can I change so it just allow 5 ~ 15 characters?

/[a-z]+[0-9]{5,15}/ doesn't work.

UPDATE Now I tried:

if(preg_match('/^[a-z0-9]{5,15}$/', strtolower($_POST['value']))) {
    echo 'Valid!';
}

else {
    echo 'NOOOOO!!!';
}

If I type "dfgdfgdfg" in the input field it will say "Valid!". The value has to have both letters and numbers, and between 5-15 characters.

like image 572
Treps Avatar asked Oct 17 '13 09:10

Treps


2 Answers

The trick is to use a positive lookahead, well in this case you'll need two.

So (?=.*[0-9]) will check if there is at least a digit in your input. What's next? You guessed it, we'll just add (?=.*[a-z]). Now let's merge it with anubhava's answer:

(?=.*[0-9])(?=.*[a-z])^[a-z0-9]{5,15}$

What does this mean in general?

  • (?=.*[0-9]) : check if there is a digit
  • (?=.*[a-z]) : check if there is a letter
  • ^ : match begin of string
  • [a-z0-9]{5,15} : match digits & letters 5 to 15 times
  • $ : match end of string

From the PHP point of view, you should always check if a variable is set:

$input = isset($_POST['value']) ? strtolower($_POST['value']) : ''; // Check if $_POST['value'] is set, otherwise assign empty string to $input

if(preg_match('~(?=.*[0-9])(?=.*[a-z])^[a-z0-9]{5,15}$~', $input)){
    echo 'Valid!';
}else{
    echo 'NOOOOO!!!';
}

Online regex demo

like image 186
HamZa Avatar answered Oct 02 '22 12:10

HamZa


Use line start and line end anchors with correct character class in your regex:

preg_match('/^[a-z0-9]{5,15}$/', strtolower($_POST['value']));

Your regex: /[a-z]+[0-9]/ will actually match 1 or more English letters and then a single digit.

like image 26
anubhava Avatar answered Oct 02 '22 13:10

anubhava