当前位置:编程学习 > php >>

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

随机生成数数字

mt_rand()函数

 代码如下 复制代码

$num = mt_rand(0,9999999);

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

 代码如下 复制代码

function random($length) {
     srand(date("s"));
     $possible_charactors = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
     $string = "";
     while(strlen($string)<$length) {
          $string .= substr($possible_charactors,(rand()%(strlen($possible_charactors))),1);
     }
     return($string);
}

例2

 代码如下 复制代码

function random_string($length, $max=FALSE)
{
  if (is_int($max) && $max > $length)
  {
    $length = mt_rand($length, $max);
  }
  $output = '';
 
  for ($i=0; $i<$length; $i++)
  {
    $which = mt_rand(0,2);
   
    if ($which === 0)
    {
      $output .= mt_rand(0,9);
    }
    elseif ($which === 1)
    {
      $output .= chr(mt_rand(65,90));
    }
    else
    {
      $output .= chr(mt_rand(97,122));
    }
  }
  return $output;
}

例3

 代码如下 复制代码

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

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

补充:Php教程,Php常用代码 
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,