php - 生成具有固定数量字母的随机字母数字字符串
问题描述
我正在尝试生成具有 0-9 数字和 a - f 字母的随机字母数字字符串,并具有以下代码:-
<?php
function random_str($length, $keyspace = '0123456789abcdef')
{
$pieces = [];
$max = mb_strlen($keyspace, '8bit') - 1;
for ($i = 0; $i < $length; ++$i) {
$pieces []= $keyspace[random_int(0, $max)];
}
return implode('', $pieces);
}
$a = random_str(64);
echo $a;
?>
但问题是它随机生成一个包含多个字母的字符串,但我想要一个总共有 64 个字符的字符串,总共必须有 26 个或 25 个字母,其余的应该是数字。它们不应该分开,而是像这样混合
7de5a1a5ae85e3aef5376333c3410ca984ef56f0c8082f9d6703414c01afbec3
任何帮助表示赞赏。
解决方案
您可以通过首先添加 25-26 个 alpha 字符来做到这一点。然后将其余的添加为数字。完成后,只需随机播放整个字符串:
function randomString()
{
// Define the result variable
$str = '';
// Generate an array with a-f
$alpha = range('a', 'f');
// Get either 25 or 26
$alphaCount = rand(25, 26);
// Add a random alpha char to the string 25 or 26 times.
for ($i = 0; $i < $alphaCount; $i++) {
$str .= $alpha[array_rand($alpha)];
}
// Check how many numbers we need to add
$numCount = 64 - $alphaCount;
// Add those numbers to the string
for ($i = 0; $i < $numCount; $i++) {
$str .= rand(0, 9);
}
// Randomize the string and return it
return str_shuffle($str);
}
这是一个演示:https ://3v4l.org/4YfsS
推荐阅读
- javascript - 关于 Object.create() 和属性继承的困惑
- angular - 将环境变量传递给 angular.json 文件。(角7)
- c# - 计时器运行时无法单击按钮C#
- java - 运行此代码时出现异常如何解决
- generics - 如何将子类型列表转换为父类型列表
- javascript - 输入答案后如何在javascript中更改用户输入颜色
- javascript - 在 .hta 文件中保留表单字段(输入/选择/复选框)。因此原始用户和/或其他用户可以打开并查看填写的信息
- wordpress - 如何使用 .htaccess 进行这项工作 - 将主域重定向到子域并将所有其他页面重定向到新域
- python-3.x - flask_wtf.csrf CSRF 令牌不匹配 - 无法修复烧瓶错误消息
- jquery - tippy 插件无法显示带有 HTML 内容的多个工具提示