在程序开发中,随机的字符串经常的使用到,比如推荐密码、订单号等等,随机密码也就是一串固定长度的字符串,这里就整理一下。
第一种
/**
* 生成随机字符串
* @param int $length 随机字符长度
* @param int $type 随机码类型:
* 0 => 数字+大小写字母
* 1 => 数字
* 2 => 小写字母
* 3 => 大写字母
* 4 => 特殊字符
* 5 => 数字+大小写字母+特殊字符
* @return string
*/
function getRandCode($length = 5, $type = 0) {
$arr = [1 => "0123456789", 2 => "abcdefghijklmnopqrstuvwxyz", 3 => "ABCDEFGHIJKLMNOPQRSTUVWXYZ", 4 => "~@#$%^&*(){}[]|"];
if($type == 0) unset($arr[4]);
$string = in_array($type, [0,5]) ? implode("", $arr) : $arr[$type];
$code = '';
for ($i = 0; $i < $length; $i++) {
$code .= $string[mt_rand(0, (strlen($string)-1))];
}
return $code;
}
第二种
/**
* 获得随机字符串
* @param string $len 需要的长度
* @param bool $special 是否需要特殊符号
* @return string 返回随机字符串
*/
function getRandCode($len, $special=true){
$chars = ["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", "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", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];
if($special){
$symbol = ["!", "@", "#", "$", "?", "|", "{", "/", ":", ";", "%", "^", "&", "*", "(", ")", "-", "_", "[", "]", "}", "<", ">", "~", "+", "=", ",", "."];
$chars = array_merge($chars, $symbol);
}
shuffle($chars); //打乱数组顺序
$str = '';
for($i=0; $i<$len; $i++){
$str .= $chars[mt_rand(0, (count($chars)-1))]; //随机取出一位
}
return $str;
}
第三种
生成32位唯一的字符串
$uniqid = md5(uniqid(microtime(true),true));
友情提示:垃圾评论一律封号...