我试图在PHP中创建一个随机字符串,我得到绝对没有输出:

<?php
    function RandomString()
    {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $randstring = '';
        for ($i = 0; $i < 10; $i++) {
            $randstring = $characters[rand(0, strlen($characters))];
        }
        return $randstring;
    }

    RandomString();
    echo $randstring;

我做错了什么?


当前回答

试试这个,它可以生成到master的长度。但它简单,适合小字符串。

$master="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$master_array = str_split($master);
shuffle($master_array);
print_r(implode("",array_slice($master_array,0,10)));

其他回答

function generateRandomString($length = 10, $hasNumber = true, $hasLowercase = true, $hasUppercase = true): string
{
    $string = '';
    if ($hasNumber)
        $string .= '0123456789';
    if ($hasLowercase)
        $string .= 'abcdefghijklmnopqrstuvwxyz';
    if ($hasUppercase)
        $string .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    return substr(str_shuffle(str_repeat($x = $string, ceil($length / strlen($x)))), 1, $length);
}

和使用:

echo generateRandomString(32);

具体回答这个问题,有两个问题:

当你回显$randstring时,它不在作用域内。 字符在循环中没有连接在一起。

以下是更正后的代码片段:

function generateRandomString($length = 10) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[random_int(0, $charactersLength - 1)];
    }
    return $randomString;
}

用下面的调用输出随机字符串:

// Echo the random string.
// Optionally, you can give it a desired string length.
echo generateRandomString();

请注意,这个答案的以前版本使用rand()而不是random_int(),因此生成可预测的随机字符串。因此,根据这个答案的建议,它被更改为更安全。

我喜欢使用openssl_random_pseudo_bytes的最后一个注释,但这对我来说不是一个解决方案,因为我仍然必须删除我不想要的字符,而且我无法获得一个设置长度的字符串。这是我的解决方案……

function rndStr($len = 20) {
    $rnd='';
    for($i=0;$i<$len;$i++) {
        do {
            $byte = openssl_random_pseudo_bytes(1);
            $asc = chr(base_convert(substr(bin2hex($byte),0,2),16,10));
        } while(!ctype_alnum($asc));
        $rnd .= $asc;
    }
    return $rnd;
}

另一个一行程序,生成一个包含字母和数字的10个字符的随机字符串。它将创建一个具有范围的数组(调整第二个参数以设置大小),循环遍历该数组并分配一个随机ASCII字符(范围0-9或a-z),然后内爆该数组以获得一个字符串。

$str = implode('', array_map(function () { return chr(rand(0, 1) ? rand(48, 57) : rand(97, 122)); }, range(0, 9)));

注意:这只适用于PHP 5.3及更高版本

递归解决方案:

public static function _random(string $set , int $length): string
{
    $setLength = strlen($set);
    $randomKey = random_int(0, $setLength - 1);

    $firstPiece = substr($set, 0, $randomKey);
    $secondPiece = substr($set, $randomKey, $setLength - $randomKey);

    $removedCharacter = $firstPiece[strlen($firstPiece) - 1] ?? null;
    if(null === $removedCharacter || $length === 0) {
        return '';
    }
    $firstPieceWithoutTheLastChar = substr($firstPiece, 0, -1);

    return $removedCharacter . self::_random($firstPieceWithoutTheLastChar . $secondPiece, $length - 1);
}

不错的表现,https://3v4l.org/aXaJ6/perf