一、php生成指定随机字符串
代码:
 
复制代码 代码示例:
/**
 * @param string $type
 * @param $length
 * @return string
 */
function randomString($type="number,upper,lower",$length){
  $valid_type = array('number','upper','lower');
  $case = explode(",",$type);
  $count = count($case);
  //根据交集判断参数是否合法
  if($count !== count(array_intersect($case,$valid_type))){
    return false;
  }
  $lower = "abcdefghijklmnopqrstuvwxyz";
  $upper = strtoupper($lower);
  $number = "0123456789";
  $str_list = "";
  for($i=0;$i<$count;++$i){
    $str_list .= $$case[$i];
  }
  return substr(str_shuffle($str_list),0,$length);
}
echo randomString("number,upper,lower",12);
二、php生成随机字符串的函数代码
此函数可创建一个随机字符串,作为用户的随机密码等。
代码:
 
复制代码 代码示例:
/************* 
*@l - length of random string 
*/ 
function generate_rand($l){ 
$c= "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; 
srand((double)microtime()*1000000); 
for($i=0; $i<$l; $i++) { 
$rand.= $c[rand()%strlen($c)]; 
} 
return $rand; 
}
三、php生成随机数或字符串
利用php生成随机数或者随机字符串的函数。
说明:
$chars 字母或数字组合。
$len表示长度
例子,php生成随机数或随机字符串。
代码:
 
复制代码 代码示例:
/** 
* 产生随机字符串 
* 
* 产生一个指定长度的随机字符串,并返回给用户 
* 
* @access public 
* @param int $len 产生字符串的位数 
* @return string 
*/ 
function randstr($len=6) { 
$chars='ABCDEFGHIJKLMNOPQRSTUVWXYZ 
abcdefghijklmnopqrstuvwxyz0123456789-@#~'; 
// characters to build the password from 
mt_srand((double)microtime()*1000000*getmypid()); 
// seed the random number generater (must be done) 
$password=''; 
while(strlen($password)<$len) 
$password.=substr($chars,(mt_rand()%strlen($chars)),1); 
return $password; 
}