简体   繁体   English

正则表达式不允许下划线

[英]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: 我不想让用户使用“ ___ ”或“ x________y ”之类的用户名,这是我刚刚编写的用于替换双下划线的函数:

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). (?!pattern) ,称为零宽度负向超前 ,将检查在字符串中从“当前位置”开始(当前位置是正则表达式引擎所在的位置) 的前面 ,无法找到该模式。 。 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}$ . 由于该组不使用文本,因此当它开始与模式[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 : 您已经使用strtolower允许使用大写的用户名了,不过,仍然可以通过添加不区分大小写的标志i直接使用regex进行验证:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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