PHP 随机字符串生成器

新手上路,请多包涵

我正在尝试在 PHP 中创建一个随机字符串,但我绝对没有输出:

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

    RandomString();
    echo $randstring;

我究竟做错了什么?

原文由 Captain Lightning 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 499
2 个回答

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

  1. $randstring 当你回显它时不在范围内。
  2. 字符没有在循环中连接在一起。

这是一个带有更正的代码片段:

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

使用以下调用输出随机字符串:

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

请注意,这会生成可预测的随机字符串。如果您想创建安全令牌, 请参阅此答案

原文由 Stephen Watkins 发布,翻译遵循 CC BY-SA 4.0 许可协议

递归解决方案:

 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

原文由 Pascual Muñoz 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题