如何使用至少一个字母,一个数字和一个特殊字符创建一个密码,并使用PHP中的正则表达式将字符串的最小长度设为8
答案 0 :(得分:0)
正则表达式对于匹配字符串很有用,而不是创建它们。
您可以使用此代码生成符合您要求的密码:
<?php
// Generate a password of length = Max(8, $len)
function generatePassword($len)
{
$lower = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z');
$upper = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z');
$specials = array('!','"','#','$','%','&','\'','(',')','*','+',',','-','.','/',':',';','<','=','>','?','@','[','\\',']','^','_','`','{','|','}','~');
$digits = array('0','1','2','3','4','5','6','7','8','9');
$all = array($lower, $upper, $specials, $digits);
$pwd = $lower[array_rand($lower, 1)];
$pwd = $pwd . $upper[array_rand($upper, 1)];
$pwd = $pwd . $specials[array_rand($specials, 1)];
$pwd = $pwd . $digits[array_rand($digits, 1)];
for($i = strlen($pwd); $i < max(8, $len); $i++)
{
$temp = $all[array_rand($all, 1)];
$pwd = $pwd . $temp[array_rand($temp, 1)];
}
return str_shuffle($pwd);
}
echo generatePassword(8);