如何使用 PHP 创建随机字符串?

新手上路,请多包涵

我知道 PHP 中的 rand 函数会生成随机整数,但是生成随机字符串的最佳方法是什么,例如:

原始字符串,9 个字符

$string = 'abcdefghi';

示例随机字符串限制为 6 个字符

$string = 'ibfeca';

更新:我发现了大量这些类型的函数,基本上我试图理解每个步骤背后的逻辑。

更新:该函数应根据需要生成任意数量的字符。

如果您回复,请评论部分。

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

阅读 398
2 个回答

好吧,您并没有澄清我在评论中提出的所有问题,但我假设您想要一个函数,该函数可以返回一串“可能”字符和一段字符串。为清楚起见,按照要求进行了彻底的评论,使用了比我通常更多的变量:

 function get_random_string($valid_chars, $length)
{
    // start with an empty random string
    $random_string = "";

    // count the number of chars in the valid chars string so we know how many choices we have
    $num_valid_chars = strlen($valid_chars);

    // repeat the steps until we've created a string of the right length
    for ($i = 0; $i < $length; $i++)
    {
        // pick a random number from 1 up to the number of valid chars
        $random_pick = mt_rand(1, $num_valid_chars);

        // take the random character out of the string of valid chars
        // subtract 1 from $random_pick because strings are indexed starting at 0, and we started picking at 1
        $random_char = $valid_chars[$random_pick-1];

        // add the randomly-chosen char onto the end of our string so far
        $random_string .= $random_char;
    }

    // return our finished random string
    return $random_string;
}

要使用您的示例数据调用此函数,您可以这样称呼它:

 $original_string = 'abcdefghi';
$random_string = get_random_string($original_string, 6);

请注意,此函数不检查传递给它的有效字符的唯一性。例如,如果您使用 'AAAB' 的有效字符字符串调用它,则为每个字母选择 A 作为 B 的可能性会高出三倍。这可能被视为错误或功能,具体取决于根据您的需要。

原文由 Chad Birch 发布,翻译遵循 CC BY-SA 2.5 许可协议

一种方法是从随机数生成 md5 并提取所需的字符数:

 <?php
    $random = substr(md5(mt_rand()), 0, 7);
    echo $random;
?>

mt_rand 将生成一个随机数, md5 将创建一个 32 个字符的字符串(包含字母和数字),在本例中,我们将提取文本的前 7 个字符。

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

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