第一种:利用字符串函数操作
代码如下:
PHP
function createRandomStr($length){
$str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';//62个字符
$strlen = 62;
while($length > $strlen){
$str .= $str;
$strlen += 62;
}
$str = str_shuffle($str);
return substr($str,$length);
}
echo createRandomStr(10);
第二种:利用数组和字符转换的思想: function createRandomStr($length){
$str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';//62个字符
$strlen = 62;
while($length > $strlen){
$str .= $str;
$strlen += 62;
}
$str = str_shuffle($str);
return substr($str,$length);
}
echo createRandomStr(10);
代码如下:
PHP
function createRandomStr($length){
$str = array_merge(range(0,9),range('a','z'),range('A','Z'));
shuffle($str);
$str = implode('',array_slice($str,$length));
return $str;
}
echo createRandomStr(10);
经过循环1000次测试,第一种效率比较高(第一种计算一千次大概0.02,第二种计算一千次大概0.06s)! 原文链接:https://www.f2er.com/php/26045.htmlfunction createRandomStr($length){
$str = array_merge(range(0,9),range('a','z'),range('A','Z'));
shuffle($str);
$str = implode('',array_slice($str,$length));
return $str;
}
echo createRandomStr(10);