加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

PHP中生成随机字符串,数字+大小写字母随机组合

发布时间:2020-12-13 21:24:23 所属栏目:PHP教程 来源:网络整理
导读:? 简单的生成随机字符串: /* * 生成随机字符串 * * $length 字符串长度 */ function random_str( $length ) { // 密码字符集,可任意添加你需要的字符 $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' ; $str = '' ; for ( $i

?

简单的生成随机字符串:

    /*
     *  生成随机字符串
     *
     *   $length    字符串长度
     */
    function random_str($length) {
        // 密码字符集,可任意添加你需要的字符
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $str = '';
        for($i = 0; $i < $length; $i++)
        {
             这里提供两种字符获取方式
            // 第一种是使用 substr 截取$chars中的任意一位字符;
            // 第二种是取字符数组 $chars 的任意元素
            $str .= substr($chars,mt_rand(0,1)">strlen($chars) - 1),1);
            $str .= $chars[mt_rand(0,strlen($chars) - 1)];
        }
        return $str;
    }

?

了解原理后可以扩展一下:

*
 * 生成随机字符串,数字,大小写字母随机组合
 *
 * @param int $length  长度
 * @param int $type    类型,1 纯数字,2 纯小写字母,3 纯大写字母,4 数字和小写字母,5 数字和大写字母,6 大小写字母,7 数字和大小写字母
 */
function random($length = 6,$type = 1)
{
     取字符集数组
    $number = range(0,9);
    $lowerLetter = range('a','z'$upperLetter = range('A','Z');
     根据type合并字符集
    if ($type == 1) {
        $charset = $number;
    } elseif ($type == 2$lowerLetter$type == 3$upperLetter$type == 4$charset = array_merge($number,1)">);
    } $type == 5$type == 6$lowerLetter,1)">$type == 7else {
        ;
    }
    ;
     生成字符串
    for ($str .= $charset[count($charset) - 1)];
         验证规则
        $type == 4 && $str) >= 2) {
            if (!preg_match('/d+/',1)">$str) || !preg_match('/[a-z]+/',1)">)) {
                $str = $str,-1);
                $i = $i - 1;
            }
        }
        $type == 5 && preg_match('/[A-Z]+/',1)">$type == 6 && $type == 7 && $str) >= 3$i - 2;
            }
        }
    }
    ;
}

?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读