php常用自建函数学习(6):获取指定长度随机字符串

//获取指定长度随机字符串
if(!function_exists('GetRandStr'))
{
    function GetRandStr($length=6)
    {
        //'!@#$%^&*()-_ []{}<>~`+=,.;:/?|';
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $random_str = '';

        for($i=0; $i<$length; $i++)
        {
            //这里提供两种字符获取方式
            //第一种是使用 substr 截取$chars中的任意一位字符;
            //第二种是取字符数组 $chars 的任意元素
            //$password .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
            $random_str .= $chars[mt_rand(0, strlen($chars) - 1)];
        }

        return $random_str;
    }
}

echo GetRandStr(16);
发布了105 篇原创文章 · 获赞 16 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_41290949/article/details/104268477