PHP正则表达式允许最多1'.' 或字符串中的'_'字符和'.' 或'_'不能在字符串的开头或结尾

skc*_*in7 2 php regex pcre expression

我正在为用户注册表单编写PHP验证.我有一个函数设置来验证使用perl兼容的正则表达式的用户名.我如何编辑它,以便正则表达式的一个要求是AT MOST一个.或_字符,但不允许字符串开头或结尾的字符?例如,"abc.d","nicholas_smith"和"20z.e"之类的东西都是有效的,但"abcd.","a_b.C"和"_nicholassmith"之类的东西都是无效的.

这是我目前拥有的,但它没有添加要求.和_字符.

function isUsernameValid()
{
    if(preg_match("/^[A-Za-z0-9_\.]*(?=.{5,20}).*$/", $this->username))
    {
        return true; //Username is valid format
    }
    return false;
}
Run Code Online (Sandbox Code Playgroud)

感谢您提供的任何帮助.

Ben*_*wee 6

if (preg_match("/^[a-zA-Z0-9]+[._]?[a-zA-Z0-9]+$/", $this->username)) {
    // there is at most one . or _, and it's not at the beginning or end
}
Run Code Online (Sandbox Code Playgroud)

您可以将其与字符串长度检查结合使用:

function isUsernameValid() {
    $length = strlen($this->username);
    if (5 <= $length && $length <= 20
    &&  preg_match("/^[a-zA-Z0-9]+[._]?[a-zA-Z0-9]+$/", $this->username)) {
        return true;
    }
    return false;
}
Run Code Online (Sandbox Code Playgroud)

你可能只使用一个正则表达式完成所有操作,但它会更难阅读.