网站地图    收藏   

主页 > php专栏 > php函数大全 >

php随机生成字符串程序方法总结 - php函数

来源:自学PHP网    时间:2014-11-25 00:26 作者: 阅读:次

[导读] 在开发中我们可以会经常碰到需要生成系统随机密码或者是登陆验证码之类的,这些数字我们肯定需要随机生成的不能定义的,下面我来总结了一些常用的在php中生成随机字符的代码,有需...

php随机生成字符串程序方法总结

在开发中我们可以会经常碰到需要生成系统随机密码或者是登陆验证码之类的,这些数字我们肯定需要随机生成的不能定义的,下面我来总结了一些常用的在php中生成随机字符的代码,有需要的朋友可参考.

随机生成数数字

mt_rand()函数,代码如下:

$num = mt_rand(0,9999999);

但如果我想随机生成字符串怎么操作,网站找到一个方法,代码如下:

  1. function random($length) {  
  2.      srand(date("s"));  
  3.      $possible_charactors = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";  
  4.      $string = "";  
  5.      while(strlen($string)<$length) {  
  6.           $string .= substr($possible_charactors,(rand()%(strlen($possible_charactors))),1);  
  7.      }  
  8.      return($string);  
  9. } 

例2,代码如下:

  1. function random_string($length, $max=FALSE) 
  2. { 
  3.   if (is_int($max) && $max > $length) 
  4.   { 
  5.     $length = mt_rand($length, $max); 
  6.   } 
  7.   $output = ''; 
  8.    
  9.   for ($i=0; $i<$length; $i++) 
  10.   { 
  11.     $which = mt_rand(0,2); 
  12.      
  13.     if ($which === 0) 
  14.     { 
  15.       $output .= mt_rand(0,9); 
  16.     } 
  17.     elseif ($which === 1) 
  18.     { 
  19.       $output .= chr(mt_rand(65,90)); 
  20.     } 
  21.     else 
  22.     { 
  23.       $output .= chr(mt_rand(97,122)); 
  24.     } 
  25.   } 
  26.   return $output; 
  27. } 

例3,代码如下:

  1. <?php 
  2. // 说明:php 中生成随机字符串的方法  
  3. // 整理:http://www.phpfensi.com  
  4. function genRandomString($len) 
  5. { 
  6.     $chars = array( 
  7.         "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",   
  8.         "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",   
  9.         "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",   
  10.         "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",   
  11.         "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",   
  12.         "3", "4", "5", "6", "7", "8", "9" 
  13.     ); 
  14.     $charsLen = count($chars) - 1; 
  15.     shuffle($chars);    // 将数组打乱  
  16.        
  17.     $output = ""; 
  18.     for ($i=0; $i<$len; $i++) 
  19.     { 
  20.         $output .= $chars[mt_rand(0, $charsLen)]; 
  21.     } 
  22.     return $output; 
  23. } 
  24. $str = genRandomString(25); 
  25. $str .= "<br />"; 
  26. $str .= genRandomString(25); 
  27. $str .= "<br />"; 
  28. $str .= genRandomString(25); 
  29. echo $str; 
  30. ?>  

注:传入的参数是你想要生成的随机字符串的长度.

自学PHP网专注网站建设学习,PHP程序学习,平面设计学习,以及操作系统学习

京ICP备14009008号-1@版权所有www.zixuephp.com

网站声明:本站所有视频,教程都由网友上传,站长收集和分享给大家学习使用,如由牵扯版权问题请联系站长邮箱904561283@qq.com

添加评论