作者:手机用户2602897765 | 来源:互联网 | 2020-08-18 06:09
在PHP中,尤其是网站程序,常常需要生成随机密码或字符串,如微信的token,API密钥,AppSecret等等,使用下面的随机字符串生成函数,便可以轻松生成你所需要的随机字符串。
在PHP中,尤其是网站程序,常常需要生成随机密码或字符串,如微信的token,API密钥,AppSecret 等等,使用下面的随机 字符串生成函数,便可以轻松生成你所需要的随机字符串。
代码如下:
/**
* 随机字符
* @param number $length 长度
* @param string $type 类型
* @param number $convert 转换大小写
* @return string
*/
function random($length=6, $type='string', $cOnvert=0){
$cOnfig= array(
'number'=>'1234567890',
'letter'=>'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
'string'=>'abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ23456789',
'all'=>'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
);
if(!isset($config[$type])) $type = 'string';
$string = $config[$type];
$code = '';
$strlen = strlen($string) -1;
for($i = 0; $i <$length; $i++){
$code .= $string{mt_rand(0, $strlen)};
}
if(!empty($convert)){
$code = ($convert > 0)? strtoupper($code) : strtolower($code);
}
return $code;
}
更多PHP相关知识,请访问PHP中文网!
以上就是PHP最强大的随机字符串生成函数的详细内容,更多请关注 第一PHP社区 其它相关文章!