PHP generate random string function (support letter case, number, Chinese)

From , 4 Years ago, written in PHP, viewed 55 times.
URL https://pastebin.vip/view/4ab52371
  1. /**
  2.  +----------------------------------------------------------
  3.  * 产生随机字串, 可用来自动生成密码,验证码,表单令牌等
  4.  * 默认长度6位 字母和数字混合 支持中文
  5.  +----------------------------------------------------------
  6.  * @param string $len 长度
  7.  * @param string $type 字串类型
  8.  * 0 字母 1 数字 其它 混合
  9.  * @param string $addChars 额外字符
  10.  +----------------------------------------------------------
  11.  * @return string
  12.  +----------------------------------------------------------
  13.  */
  14. function rand_string($len = 6, $type = '', $addChars = '') {
  15.         $str = '';
  16.         switch ($type) {
  17.                 case 0 :
  18.                         $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' . $addChars;
  19.                         break;
  20.                 case 1 :
  21.                         $chars = str_repeat('0123456789', 3);
  22.                         break;
  23.                 case 2 :
  24.                         $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' . $addChars;
  25.                         break;
  26.                 case 3 :
  27.                         $chars = 'abcdefghijklmnopqrstuvwxyz' . $addChars;
  28.                         break;
  29.                 default :
  30.                         // 默认去掉了容易混淆的字符oOLl和数字01,要添加请使用addChars参数
  31.                         $chars = 'ABCDEFGHIJKMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789' . $addChars;
  32.                         break;
  33.         }
  34.         if ($len > 10) { //位数过长重复字符串一定次数
  35.                 $chars = $type == 1 ? str_repeat($chars, $len) : str_repeat($chars, 5);
  36.         }
  37.         if ($type != 4) {
  38.                 $chars = str_shuffle($chars);
  39.                 $str = substr($chars, 0, $len);
  40.         } else {
  41.                 // 中文随机字
  42.                 for ($i = 0; $i < $len; $i++) {
  43.                         $str .= msubstr($chars, floor(mt_rand(0, mb_strlen($chars, 'utf-8') - 1)), 1);
  44.                 }
  45.         }
  46.         return $str;
  47. }
  48.  

Reply to "PHP generate random string function (support letter case, number, Chinese)"

Here you can reply to the paste above

captcha

https://burned.cc - Burn After Reading Website