php 产生随机字串,可用来自动生成密码 默认长度6位 字母和数字混合

180it 2021-11-05 PM 1371℃ 0条
/**
 * 产生随机字串,可用来自动生成密码 默认长度6位 字母和数字混合
 * 
 * @param string $len 长度
 * @param string $type 字串类型:0 字母 1 数字 2 大写字母 3 小写字母  4 中文  
 * 其他为数字字母混合(去掉了 容易混淆的字符oOLl和数字01,)
 * @param string $addChars 额外字符
 * @return string 
 */
function rand_string($len = 4, $type='checkCode'){
    $str = '';
    switch ($type) {
        case 1://数字
            $chars = '0123456789';
            break;
        case 2://大写字母
            $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
            break;
        case 3://小写字母
            $chars = 'abcdefghijklmnopqrstuvwxyz';
            break;
        case 4://大小写中英文
            $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
            break;
        default: 
            // 默认去掉了容易混淆的字符oOLl和数字01,要添加请使用addChars参数
            $chars = 'ABCDEFGHIJKMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789';
            break;
    }
    if ($len > 10) { // 位数过长重复字符串一定次数
        $chars = $type == 1 ? str_repeat($chars, $len) : str_repeat($chars, 5);
    } 
    if ($type != 4) {
        $chars = str_shuffle($chars);
        $str = substr($chars, 0, $len);
    } else {
        // 中文随机字
        for($i = 0; $i < $len; $i ++) {
            $str .= msubstr($chars, floor(mt_rand(0, mb_strlen($chars, 'utf-8') - 1)), 1);
        } 
    } 
    return $str;
} 

支付宝打赏支付宝打赏 微信打赏微信打赏

如果文章或资源对您有帮助,欢迎打赏作者。一路走来,感谢有您!

标签: none

php 产生随机字串,可用来自动生成密码 默认长度6位 字母和数字混合