之前做过取随机数和生成验证码的练习,都是通过取随机数作为数组下标,然后从数组中取值的方式(js):
1 /*验证码*/ 2 function sj_yzm(){ 3 //存一个包括数字和字母的数组 4 var zongArr = ['a','b','c','d','e','f','g','H','I','G','K','L','M','N','0','1','2','3','4','5','6','7','8','9']; 5 //定义一个用来存放验证码的数组 6 var yzmArr = []; 7 //找到验证码显示框 8 var yzm = document.getElementsByClassName('yzm_sj')[0]; 9 //生成四个随机数从zongArr挑出数字并为验证码数组赋值 10 for(var i = 0; i < 4; i++){ 11 var sjs =parseInt(Math.random()*24); 12 yzmArr[i] = zongArr[sjs]; 13 } 14 //将验证码数组遍历,拼接为字符串,输出 15 var each = ''; 16 for(var j = 0; j < yzmArr.length; j++){ 17 each += yzmArr[j]; 18 } 19 yzm.innerHTML = each; 20 }
在php中还有其他几种方便好用的方法:
1.取当前时间戳,用md5加密,取值
1 view plain copy 2 3 function get_password( $length = 8 ) 4 { 5 $str = substr(md5(time()), 0, $length);//md5加密,time()当前时间戳 6 return $str; 7 }
2.用mt_rand():
1 function GetRandStr($length){ 2 $str='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; 3 $len=strlen($str)-1; 4 $randstr=''; 5 for($i=0;$i<$length;$i++){ 6 $num=mt_rand(0,$len); 7 $randstr .= $str[$num]; 8 } 9 return $randstr; 10 } 11 $number=GetRandStr(6); 12 echo $number;
3.打乱字符串取值:
1 function getrandstr(){ 2 $str='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890'; 3 $randStr = str_shuffle($str);//打乱字符串 4 $rands= substr($randStr,0,6);//substr(string,start,length);返回字符串的一部分 5 return $rands; 6 }