1 <?php 2 /** 3 * 随机返回字符串 4 * @param number 返回字符串长度 5 * @param string 从哪些字符串中随机返回,已设置默认字符串,可空 6 * @return string 返回随机字符串 7 */ 8 function random_string($length = 8, $chars = null) { 9 static $s; 10 if( empty($chars) ) $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; 11 while( strlen($s) < $length) { 12 $s .= substr($chars, rand(0, strlen($chars) - 1), 1); 13 } 14 return $s; 15 } 16 17 function random_string2($length = 8, $chars_range = 'alpha-number') { 18 $str = ''; 19 $chars = ''; 20 $char_arr = array( 21 "alpha" => "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", 22 "number" => "0123456789", 23 ); 24 if (empty($chars_range)) { 25 $chars_rang = 'alpha-number'; 26 } 27 if(strpos($chars_range, '-')) { 28 $char_range_arr = explode('-',$chars_range); 29 foreach($char_range_arr as $range){ 30 if(!array_key_exists($range, $char_arr)){ 31 exit("wrong range \"". $range ."\""); 32 } 33 $chars .= $char_arr[$range]; 34 } 35 }else{ 36 if(!array_key_exists($chars_range, $char_arr)){ 37 exit("wrong range \"".$chars_range ."\""); 38 } 39 $chars = $char_arr[$chars_range]; 40 } 41 while( strlen($str) < $length) { 42 $str .= substr($chars, rand(0, strlen($chars) - 1), 1); 43 } 44 return $str; 45 } 46 47 ?>