我想使用preg_math函数验证输入的密码是否符合我的复杂性和长度规则:
if (!preg_match('/(?=.*[A-Za-z])(?=.*[0-9])(?=.*[^a-zA-Z0-9])/', $password)) {
$errors[] = 'Password allows alpha-numerical sumbols and should contain number and letters between 6-24 symbols';
}
但是此功能无法正常工作。由于我的密码应至少包含一个数字(0-9)和一个字母(az)或符号(,),_, - 介于6到20个符号之间。< / p>
如何编写正则表达式? 谢谢!
答案 0 :(得分:0)
您正在比较整个字符串 使用strpos:http://php.net/manual/en/function.strpos.php
$password = "test!";
//Enter characters you want to check for
$characters = "/(!?=.*[A-Za-z])(?=.*[0-9])(?=.*[^a-zA-Z0-9])/";
//Split into array to check each character
$chars = str_split($characters);
//Set wrong password by default and check for correct characters
$correctPassword = false;
//Check each character
foreach($chars as $char){
//If characters have been found, set password as correct
if (strpos($password, $char))
{
$correctPassword = true;
}
}
//Also check for length, equal or greater then 6, smaller or equal to 20
if ( ($correctPassword) && ( strlen($password) >= 6 ) && ( strlen($password) <= 20 ) )
{
echo "OK";
}
else
{
echo "Password Unsafe";
}
希望这会有所帮助:)
如果这是您搜索的答案,请标记为答案。
答案 1 :(得分:0)
您需要添加锚点并限制字符数,这是一种完成工作的方法:
preg_match('/^(?=.*[A-Za-z])(?=.*[0-9])(?=.*[^a-zA-Z0-9]).{6,20}$/', $password)