PHP生成随机或者唯一字符串

时间:2021-09-11 02:13:02

本文出至:新太潮流网络博客

/**
* [生成随机字符串]
* @E-mial wuliqiang_aa@163.com
* @TIME 2017-04-07
* @WEB http://blog.iinu.com.cn
* @param integer $length [生成的长度]
* @param integer $type [生成的类型]
* @return [type] str [description]
* @php 随机码类型:0,数字+大写字母;1,数字;2,小写字母;3,大写字母;4,特殊字符;-1,数字+大小写字母+特殊字符
*/
function randCode($length = 5, $type = 0) {
$arr = array(1 => "0123456789", 2 => "abcdefghijklmnopqrstuvwxyz", 3 => "ABCDEFGHIJKLMNOPQRSTUVWXYZ", 4 => "~@#$%^&*(){}[]|");
if ($type == 0) {
array_pop($arr);
$string = implode("", $arr);
} else if ($type == "-1") {
$string = implode("", $arr);
} else {
$string = $arr[$type];
}
$count = strlen($string) - 1;
for ($i = 0; $i < $length; $i++) {
$str[$i] = $string[rand(0, $count)];
$code .= $str[$i];
}
return $code;
}

/**
* [生成唯一字符串]
* @E-mial wuliqiang_aa@163.com
* @TIME 2017-04-07
* @WEB http://blog.iinu.com.cn
* @ 0-存数字字符串;1-小写字母字符串;2-大写字母字符串;3-大小写数字字符串;4-字符;
* 5-数字,小写,大写,字符混合
* @param integer $type [字符串的类型]
* @param integer $length [字符串的长度]
* @param integer $time [是否带时间1-带,0-不带]
* @return [string] $str [返回唯一字符串]
*/
function randSole($type = 0,$length = 18,$time=0){
$str = $time == 0 ? '':date('YmdHis',time());
switch ($type) {
case 0:
for((int)$i = 0;$i <= $length;$i++){
if(mb_strlen($str) == $length){
$str = $str;
}else{