Aram Gevorgyan
Aram Gevorgyan

Reputation: 511

check username by regexp

for my registration i check username with my regex -- Username must contain more than 3 and less than 20 characters. Also username can contain only lphanumeric characters and " _ ", " . ", " - ".

/^([\w\.\-]{3,20})$/isu.

Now i want to check (p-) too, if this exist return false username cant content (p-)

private $regExpUsername = "/^([\w\.\-]{3,20})$/isu";

    private function checkUsername($username){
        if(!preg_match($this->regExpUsername, $username)){
            $this->addError(ERR_ENTER_USERNAME);
        }
    }

Upvotes: 0

Views: 89

Answers (1)

stema
stema

Reputation: 93026

I understood that you don't want the username to end with a -. This would be this

^[\w.-]{2,19}[\w.]$

Since \w contains the underscore this would allow the username to end with an underscore, but not with a dash, since the dash is not part of the character class, that defines the last character.

See it here on Regexr

As zerkms commented the s modifier makes no sense here, because it changes the behaviour of the . special character that you don't use.

Also the i modifier makes no sense, it would match lower and uppercase letters, but you don't use letters to define your expression.

Update

Then you need a negative lookahead

^(?!.*p-)[\w.-]{3,20}$

(?!.*p-) is a negative lookahead, this assertion will fail as soon as there is a p- anywhere in the string.

See it here on Regexr

Upvotes: 3

Related Questions