首页 > 解决方案 > 生成具有固定数量字母的随机字母数字字符串

问题描述

我正在尝试生成具有 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

任何帮助表示赞赏。

标签: phpstring

解决方案


您可以通过首先添加 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


推荐阅读