Search code examples
phpregextwitter

RegEx for Twitter username not working


The following regular expression function for validating a Twitter username is not working because a twitter name can be a minimum of 1 character and a maximum of 20. However, when I tested this, it allows usernames greater than 20 characters. Where did I go wrong?

public function val_username($subject)
{
    return (bool)preg_match('/[a-zA-Z0-9_]{1,20}/', $subject);      
}

Solution

  • You forgot the $ and ^

    /^[a-zA-Z0-9_]{1,20}$/ should work

    public function val_username($subject)
    {
        return (bool)preg_match('/^[a-zA-Z0-9_]{1,20}$/', $subject);      
    }