经常需要生成很多格式的字符串很是烦人,自己写了一个:php随机生成指定位数的字符串函数。写的比较随便,建议大家自定义更多!
直接贴代码了:
/**
* @param $length,指定字符串的长度
* @param string $type,制定字符串的类型,(number、letter、mixed、custom)大家有兴趣可以拓展一下,起名字太伤神
* @param string $custom_str,自定义的字符串
* @return string,返回的字符串
*/
function createRandomStr($length,$type='number',$custom_str='0123456789'){
if($type==='number'){
$str = '0123456789';
}
if($type==='letter'){
$str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
}
if($type==='mixed'){
$str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
}
if($type==='custom'){
$str = $custom_str;
}
$str_length = strlen($str);
while ($length>$str_length){
$str .= $str;
$str_length += $str_length;
}
$str = str_shuffle($str);
return substr($str,0,$length);
}
使用方法示例:
//生成一个随机imei号码:863908021544309
echo ’86’.createRandomStr(13,’number’);