使用Regex验证密码

时间:2015-07-31 03:15:39

标签: php regex

我正在尝试为每种类型获取不同的错误:缺少大写,缺少小写,缺少数字或空格。长度似乎是唯一有效的。我猜是因为它是在代码的开头。我尝试了不同的变化,似乎无法让它发挥作用。

    <?php
    $Passwords = array(
"F!ve5",
"This !s12",
"w!zard12",
"W!ZARD12",
"W!zardJK",
"Wizard12",
"!Qazxsw2",
"@Wsxzaq1",
"@Wsxcde3",
"#Edcxsw2");

foreach ($Passwords as $StongPass) {
echo "<p>The Password &ldquo;" . $StongPass .
    "&rdquo; </p>";
if (strlen($StongPass)<8) 
    echo "Password is to short!";

elseif (strlen($StongPass)>16)
    echo "Password is to long!";

elseif (preg_match('/P[A-Z]/', $StongPass)) 
    echo "Password does not contain an upper case letter!";

elseif (preg_match('/P[a-z]/', $StongPass)) 
    echo "Password does not contain a lower case letter!";

elseif (preg_match('/P[!@#$%^&*()\-_=+{};:,<.>]/', $StongPass)) 
    echo "Password does not contain a special letter!";

elseif (preg_match('/P[0-9]/', $StongPass)) 
    echo "Password does not contain a number!";

elseif (preg_match('/P[""]/', $StongPass)) 
    echo "Password cannot contain any spaces!";

else 
    echo "Password is strong!";

    }
    ?>

结果看起来像这样  “密码”F!ve5“ 密码是短的! 密码“这!s12” 密码很强! 密码“w!zard12” 密码很强! 密码“W!ZARD12” 密码很强!“

2 个答案:

答案 0 :(得分:3)

这里有很多PHP代码是多余的,因为整个验证可以通过使用一系列前瞻组在一个正则表达式中完成。

使用此模式

console.log(compare(userChoice, computerChoice));

每个组(在括号之间)匹配以下字符串中某处所需验证的元素,然后重置下一组的指针。因此,字符串必须匹配模式中的每个组才能通过。

分解为我们得到的组件

/^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[,;:])(?=.{8,16})(?!.*[\s])/

在PHP中,这将成为

^            Make sure we start at the beginning of the string.
(?=.*[A-Z])  Match A-Z in the string
(?=.*[a-z])  Match a-z (separate, since we want at least one of each)
(?=.*[0-9])  Match 0-9
(?=.*[,;:])  Match comma, semicolon or colon. Add additional special characters as required
(?=.{8,16})  Match length between 8 and 16 characters
(?!.*[\s])   Match if whitespace *does not* appear.

可替换地:

$pattern = '/^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[,;:])(?=.{8,16})(?!.*[\s])/'
$str = "Ab0:padding";
if (preg_match($pattern, $str)) {    //true
  // do stuff
} else {
  // Do other stuff
}

here

的例子

感谢Alan Moore this answer构成了上述基础。

答案 1 :(得分:1)

大写P在正则表达式中没有特殊含义。这有点乱。注意在某些情况下使用!preg_match()。我完全重写了符号检查,因为它们中的许多具有特殊含义,使用ASCII图表对它们进行分组更容易。

if (strlen($StongPass)<8) 
    echo "Password is to short!";

elseif (strlen($StongPass)>16)
    echo "Password is to long!";

elseif (!preg_match('/[A-Z]/', $StongPass)) 
    echo "Password does not contain an upper case letter!";

elseif (!preg_match('/[a-z]/', $StongPass)) 
    echo "Password does not contain a lower case letter!";

elseif (!preg_match('/[!-\/:-@[-`{-~]/', $StongPass)) 
    echo "Password does not contain a special letter!";

elseif (!preg_match('/\d/', $StongPass)) 
    echo "Password does not contain a number!";

elseif (preg_match('/\s/', $StongPass)) 
    echo "Password cannot contain any spaces!";

else 
    echo "Password is strong!";