Search code examples
phpregexpreg-match

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.


Solution

  • 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