Php 生成随机字符串函数集成
程序员文章站
2022-07-14 19:49:28
...
通过 uniqid() 获取随机字符串
if (! function_exists('uniqid_nonce_str')) {
/**
* 通过 uniqid() 获取随机字符串
*
* @param int $sizeType 1 13位 2 32位 default ''
* @return string
*/
function uniqid_nonce_str(int $sizeType = 1) : string
{
if ($sizeType == 1) {
return uniqid();
} elseif ($sizeType == 2) {
return md5(uniqid(microtime(true), true));
} else {
return '';
}
}
}
通过 str_shuffle() 获取随机字符串
if (! function_exists('shuffle_char_nonce_str')) {
/**
* 通过 str_shuffle() 获取随机字符串
*
* @param int $length [default '']
* @param string $extra
* @return string
*/
function shuffle_char_nonce_str(int $length = 32, string $extra = '') : string
{
$predefine = 'qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM0147896325';
if (0 < $length && $length <= strlen($predefine . $extra)) {
return substr(str_shuffle($predefine . $extra), mt_rand(0, strlen($predefine . $extra) - $length), $length);
} else {
return '';
}
}
}
通过 shuffle() 处理预定义数组,获取随机字符串
if (! function_exists('shuffle_nonce_str')) {
/**
* 通过 shuffle() 处理预定义数组,获取随机字符串
*
* @param int $length [default '']
* @param array $extra
* @return string
*/
function shuffle_nonce_str(int $length = 32, array $extra = []) : string
{
$predefine = [
"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"
];
$current = array_merge($predefine, $extra);
$counter = count($current);
shuffle($current);
if (0 < $length && $length <= $counter) {
return implode('', array_slice($current, mt_rand(0, $counter - $length), $length));
} else {
return '';
}
}
}
转载本文,请注明出处、作者。