Search code examples
phpregexpreg-matchlowercase

PHP preg_match and regex: lowercaps only either with hyphens, numbers, or alphabets, and at least 6 characters?


I want to accept an input with lowercaps only either with hyphens, numbers, or alphabets, and at least 6 characters. But the regex below accepts Upper case as long as the input is longer than 6 characters.

$user_name = 'BloggerCathrin';

if(!preg_match('/([a-z0-9]{6}|[a-z0-9\-]{6})/', $user_name))
{
    echo 'please use lowercaps only, either with hyphens, numbers, or alphabets, and at least 6 characters.';
}

How can I fix that?


Solution

  • If you pattern needs to match the whole string - from beginning to end - you need to wrap it inside ^ and $:

          /^([a-z0-9]{6}|[a-z0-9\-]{6})$/
    start -´                           `- end
    

    From PCRE regex syntax - Meta-characters :

    ^ - assert start of subject (or line, in multiline mode)
    $ - assert end of subject or before a terminating newline (or end of line, in multiline mode)


    If you have a six character minimum (and you also can compact), your pattern might look like:

     /^[a-z0-9-]{6,}$/
                 ```- minimum: 6, maximum: unspecified (empty)