PHP-正则表达式,用于验证具有1个大写字母、任意数量的小写字母和至少1个数字的用户名


PHP - regular expression to validate a username with 1 uppercase, any number of lowercase and at least 1 number?

我的代码是:

$user_patt = "/^[A-Za-z0-9]{8,20}$/";

然而,当我使用preg_match来验证格式时:

if (preg_match("/user/i", $field)) {
    if (!preg_match($user_patt, $value)) {
        $error_array[] = "$value is an invalid $field";
   }
}

然后,我在注册一个名称时不断收到错误,例如Granted42。我错过什么了吗?

使用3个正则表达式怎么样?

if (!(preg_match('/^[A-Za-z0-9]{8,20}$/', $value) &&  
      preg_match('/[A-Z]/', $value) &&
      preg_match('/[0-9]/', $value))) 
{
    $error_array[] = "$value is an invalid $field";
}

如果必须只使用一个正则表达式,可以尝试:

if (preg_match('/^[A-Za-z0-9]*[A-Z][A-Za-z0-9]*[0-9][A-Za-z0-9]*|[A-Za-z0-9]*[0-9][A-Za-z0-9]*[A-Z][A-Za-z0-9]*/', $value)) {
    $error_array[] = "$value is an invalid $field";
}

这只是简单地说明,要么在数字之前出现大写字母,要么相反,但它不再满足8到20个字符的要求。

如果您不想要除字母和数字之外的任何其他字符:

$user_patt = '/^(?=.*[A-Z])(?=.*[a-z])(?=.*'d)[a-zA-Z0-9]{8,20}$/';
if (!preg_match($user_patt, $value)) {
    $error_array[] = "$value is an invalid $field";
} 

这应该对您有效。我已经更新了它,以查找8到20个字符,并且至少需要一个上、下和数字。它也不允许包含空格的非字母数字字符。

$user_patt = '/^((?!.*[^a-zA-Z'd])(?=.*[A-Z])(?=.*[a-z])(?=.*'d).{8,20})$/';
if (!preg_match($user_patt, $value)) {
    $error_array[] = "$value is an invalid $field";
}