Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression to only allow lower-case letters [duplicate]

Tags:

regex

php

Possible Duplicate:
Regular Expressions: low-caps, dots, zero spaces

How could I change the regular expression below to only allow lower-case letters?

function valid_username($username, $minlength = 3, $maxlength = 30)
{

    $username = trim($username);

    if (empty($username))
    {
        return false; // it was empty
    }
    if (strlen($username) > $maxlength)
    {
        return false; // to long
    }
    if (strlen($username) < $minlength)
    {

        return false; //toshort
    }

    $result = ereg("^[A-Za-z0-9_\-]+$", $username); //only A-Z, a-z and 0-9 are allowed

    if ($result)
    {
        return true; // ok no invalid chars
    } else
    {
        return false; //invalid chars found
    }

    return false;

}
like image 867
John Avatar asked Jan 01 '13 01:01

John


2 Answers

You have both A-Z and a-z in your character class, just omit the A-Z to only allow for the a-z (lowercase) letters. I.e.

"^[a-z0-9_\-]+$"
like image 53
Dave Avatar answered Oct 13 '22 00:10

Dave


You just remove the A-Z from the regular expression.

Also, since you are already using a regular expression you can just put everything into it, like this:

function valid_username($username, $minlength = 3, $maxlength = 30)
{
    $regex = "/^[a-z0-9_\-]{{$minlength},{$maxlength}}$/";

    return preg_match($regex, trim($username)) === 1;
}

It will make sure that the username is not empty, is of the permitted length, and that it only contains allowed characters.

like image 23
Sverri M. Olsen Avatar answered Oct 12 '22 23:10

Sverri M. Olsen