不言不语

您现在的位置是: 首页 >  PHP

PHP

PHP最强大的随机字符串生成函数

2022-05-31PHP
​在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;
}



文章评论