php语言

PHP生成随机字符串的技巧

时间:2024-12-29 23:54:28 php语言 我要投稿
  • 相关推荐

PHP生成随机字符串的技巧

  使用PHP开发应用程序,尤其是网站程序,常常需要生成随机密码,而本文收集整理了几种生成随机字符串的方法,希望对您有所帮助。

  例子1:

  复制代码 代码如下:

  < ?php

  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;

  ?>

  例子2:

  复制代码 代码如下:

  <?php

  /* Generate Password

  * Length : 8

  */

  $str = "0123456789abcdefghijklmnopqrstuvwxyz";   //   输出字符集

  $n = 8;   //   输出串长度

  $len = strlen($str)-1;

  for($j=0 ; $j<200 ; $j++){

  for($i=0 ; $i<$n; $i++){

  $s .=  $str[rand(0,$len)];

  }

  echo $s . "<br/>";

  $s = "";

  }

  ?>

【PHP生成随机字符串的技巧】相关文章:

PHP简单生成随机字符串10-30

PHP生成自定义长度随机字符串实例07-22

php如何生成随机密码07-01

PHP生成随机密码的方法11-06

php怎么生成随机密码10-29

如何给php生成随机密码09-09

使用PHP批量生成随机用户名10-17

php生成随机密码的几种方法07-11

php生成N个不重复的随机数07-27