随机生成字符串作为

php如何生成不重复随机字符串

编程开发 2020-09-27 02:54:39 42

导读

php生成不重复随机字符串的方法:1、使用时间戳作为原始字符串,再随机生成五个字符随机插入任意位置,生成新的字符串,保证不重复function rand($len) { $chars='ABCDEFGHIJKLMNOPQRST……

php生成不重复随机字符串的方法:

1、使用时间戳作为原始字符串,再随机生成五个字符随机插入任意位置,生成新的字符串,保证不重复

function rand($len)
    {
        $chars='ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
        $string=time();
        for(;$len>=1;$len--)
        {
            $position=rand()%strlen($chars);
            $position2=rand()%strlen($string);
            $string=substr_replace($string,substr($chars,$position,1),$position2,0);
        }
        return $string;
    }

2、使用array_slice()函数随机抽取

<?php
$numbers = range (1,50);
//shuffle 将数组顺序随即打乱
shuffle ($numbers);
//array_slice 取该数组中的某一段
$num=6;
$result = array_slice($numbers,0,$num);
print_r($result);
?>


1253067 TFnetwork_cn