如何使用PHP创建随机字符串? [英] How to create a random string using PHP?

查看:97
本文介绍了如何使用PHP创建随机字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道PHP中的rand函数会生成随机整数,但是生成诸如以下这样的随机字符串的最佳方法是什么?

I know that the rand function in PHP generates random integers, but what is the best way to generate a random string such as:

原始字符串(9个字符)

$string = 'abcdefghi';

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

$string = 'ibfeca';

更新:我发现了很多这类功能,基本上我想了解每一步背后的逻辑.

UPDATE: I have found tons of these types of functions, basically I'm trying to understand the logic behind each step.

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

UPDATE: The function should generate any amount of chars as required.

如果您回复,请评论这些部分.

Please comment the parts if you reply.

推荐答案

好吧,您并没有阐明我在评论中提出的所有问题,但是我假设您想要一个可以使用字符串可能的"字符和要返回的字符串长度.为了清楚起见,按要求进行了彻底注释,使用了比我通常更多的变量:

Well, you didn't clarify all the questions I asked in my comment, but I'll assume that you want a function that can take a string of "possible" characters and a length of string to return. Commented thoroughly as requested, using more variables than I would normally, for clarity:

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;
}

要使用示例数据调用此函数,应将其命名为:

To call this function with your example data, you'd call it something like:

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

请注意,此函数不会检查传递给它的有效字符中的唯一性.例如,如果使用有效的'AAAB'字符字符串进行调用,则为每个字母选择A作为B的可能性将增加三倍.根据您的需要,可以将其视为错误或功能.

Note that this function doesn't check for uniqueness in the valid chars passed to it. For example, if you called it with a valid chars string of 'AAAB', it would be three times more likely to choose an A for each letter as a B. That could be considered a bug or a feature, depending on your needs.

这篇关于如何使用PHP创建随机字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆