生成具有固定字母数的随机字母数字字符串

时间:2019-07-01 06:51:31

标签: php string

我正在尝试生成随机字母数字字符串,其数字为0-9,字母为-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

感谢您的帮助。

4 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

您可以尝试生成包含26个字母和其余数字的随机字符串。希望对您有帮助!

    function random_str() {
        $aplhabets = str_split('abcdefghijklmnopqrstuvwxyz');
        shuffle($aplhabets); // probably optional since array_is randomized; this may be redundant
        $rand_str = '';
        foreach (array_rand($aplhabets, 26) as $k)
            $rand_str .= $seed[$k];

        $digits = str_split('0123456789'); // and any other characters
        foreach (array_rand($digits, 38) as $j)
            $rand_str .= $digits[$j];

        return shuffle($rand_str);
   }

答案 2 :(得分:0)

尝试一下:

function generate_random_string($type = 'alnum', $length = 16) {
        switch ($type) {
            case 'alpha' : $pool = 'ABCDEFGHJKLMNPQRSTUVWXYZ';
                break;
            case 'alnum' : $pool = '0123456789abcdef';
                break;
            case 'numeric' : $pool = '23456789';
                break;
        }
        $str = '';
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($pool, mt_rand(0, strlen($pool) - 1), 1);
        }
        return $str;
    }

答案 3 :(得分:0)

<?php
function getName($n, $characters) {
    $randomString = '';

    for ($i = 0; $i < $n; $i++) {
        $index = rand(0, strlen($characters) - 1);
        $randomString .= $characters[$index];
    }

    return $randomString;
}

$result = '';
$letters = getName(25, 'abcdef');
$numbers = getName(39, '0123456789');
$result = str_shuffle($letters . $numbers);
var_dump($result);

?>

返回:

string(64) "65517e5b9910a15313695b1ebb3e53b56b47802afdcb4b0d3b141eb3cae8f2a7"