简体   繁体   中英

Regular Expression not allow duble underscores

I am writing my website user registration part, I have a simple regular expression as follows:

if(preg_match("/^[a-z0-9_]{3,15}$/", $username)){
    // OK...
}else{
    echo "error";
    exit();
}

I don't want to let users to have usernames like: ' ___ ' or ' x________y ', this is my function which I just wrote to replace duble underscores:

function replace_repeated_underScores($string){
    $final_str = '';
    $str_len = strlen($string);
    $prev_char = '';
    for($i = 0; $i < $str_len; $i++){
        if($i > 1){
            $prev_char = $string[$i - 1];
        }
        $this_char = $string[$i];
        if($prev_char == '_' && $this_char == '_'){

        }else{
            $final_str .= $this_char;
        }
    }
    return $final_str;
}

And it works just fine, but I wonder if I could also check this with regular expression and not another function.

I would appreciate any help.

Just add negative look-ahead to check whether there is double underscore in the name or not.

/^(?!.*__)[a-z0-9_]{3,15}$/

(?!pattern) , called zero-width negative look-ahead , will check that it is not possible to find the pattern, ahead in the string from the "current position" (current position is the position that the regex engine is at). It is zero-width , since it doesn't consume text in the process, as opposed to the part outside. It is negative, since the match would only continue if there is no way to match the pattern (all possibilities are exhausted).

The pattern is .*__ , so it simply means that the match will only continue if it cannot find a match for .*__ , ie no double underscore __ ahead in the string. Since the group does not consume text, you will still be at the start of the string when it starts to match the later part of the pattern [a-z0-9_]{3,15}$ .

You already allow uppercase username with strtolower , nevertheless, it is still possible to do validation with regex directly by adding case-insensitive flag i :

/^(?!.*__)[a-z0-9_]{3,15}$/i

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM