随机字符串是编程过程中经常用到的函数,下面提供5个方法可以供参考
方法一:
/**
* 随机字符串
* @param int $length
* @return string
*/
function createNonceStr($length = 16) {
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$str = "";
for ($i = 0; $i < $length; $i++) {
$str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
}
return $str;
}方法二:
/**
* @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[mt_rand(0, $len - 1)];
}
$tokenvalue = $randStr;
if ($addtime) {
$tokenvalue = $randStr . time();
}
return $tokenvalue;
}方法四:
function create_password($pw_length = 6)
{
$randpwd = '';
for ($i = 0; $i < $pw_length; $i++)
{
$randpwd .= chr(mt_rand(33, 126));
}
return $randpwd;
}方法五:
function make_password( $length = 8 )
{
// 密码字符集,可任意添加你需要的字符
$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′, ‘!',
‘@','#', ‘$', ‘%', ‘^', ‘&', ‘*', ‘(‘, ‘)', ‘-', ‘_',
‘[', ']‘, ‘{‘, ‘}', ‘<', ‘>', ‘~', ‘`', ‘+', ‘=', ‘,',
‘.', ‘;', ‘:', ‘/', ‘?', ‘|');
// 在 $chars 中随机取 $length 个数组元素键名
$keys = ($chars, $length);
$password = ”;
for($i = 0; $i < $length; $i++)
{
// 将 $length 个数组元素连接成字符串
$password .= $chars[$keys[$i]];
}
return $password;
}