ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
~~~ <?php /** * ======================================= * Created by Zhihua_W. * Author: Zhihua_W * Date: 2016/12/1 0004 * Time: 下午 5:15 * Project: PHP开发小技巧 * Power: 两种方法实现获取随机字符串 * ======================================= */ /** * 方法一:获取随机字符串 * @param number $length 长度 * @param string $type 类型 * @param number $convert 转换大小写 * @return string 随机字符串 */ function random($length = 6, $type = 'string', $convert = 0) { $config = array( 'number' => '1234567890', 'letter' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', 'string' => 'abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ23456789', 'all' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890' ); if (!isset($config[$type])) $type = 'string'; $string = $config[$type]; $code = ''; $strlen = strlen($string) - 1; for ($i = 0; $i < $length; $i++) { $code .= $string{mt_rand(0, $strlen)}; } if (!empty($convert)) { $code = ($convert > 0) ? strtoupper($code) : strtolower($code); } return $code; } /** * 方法二:获取随机字符串 * @param int $randLength 长度 * @param int $addtime 是否加入当前时间戳 * @param int $includenumber 是否包含数字 * @return string */ function rand_str($randLength = 6, $addtime = 1, $includenumber = 0) { if ($includenumber) { $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHJKLMNPQEST123456789'; } else { $chars = 'abcdefghijklmnopqrstuvwxyz'; } $len = strlen($chars); $randStr = ''; for ($i = 0; $i < $randLength; $i++) { $randStr .= $chars[rand(0, $len - 1)]; } $tokenvalue = $randStr; if ($addtime) { $tokenvalue = $randStr . time(); } return $tokenvalue; } //其中也可以放多个参数 //random(4,'number'); //random(6,'letter',1); echo random(10); //方法二同样 echo rand_str(6); ?> ~~~