开发者

generate a 5 char long string 0-9 a-z

开发者 https://www.devze.com 2022-12-15 02:44 出处:网络
I need a function in 开发者_运维技巧php that can generate a 5 char long string with numbers and a-z

I need a function in 开发者_运维技巧php that can generate a 5 char long string with numbers and a-z

What should I look into?


Other's have already provided you with correct answers, but here's a one-liner, just for the sake of it:

$code = substr(str_shuffle('0123456789abcdefghijklmnopqrstuvwxyz'), 0, 5);

str_shuffle randomizes the above string, then substr takes the first 5 letters of that shuffled string. Simple.


As noted in comments for this answer, this function only generates strings that have only unique characters. If one would like to have the strings where even "aaaaa" is possible, here's a little function that allows just that:

function generate($len) {
    return substr(str_shuffle(str_repeat('0123456789abcdefghijklmnopqrstuvwxyz', $len)), 0, $len);
}

echo generate(5);

str_repeat repeats the 0-9a-z string $len times, so every letter has an almost equal possibility for every position. (Read the comments on why only "almost")


For kicks, here's an alternate approach:

//create a random base 36 string
$str = base_convert(rand(), 10, 36);

substr and concatenate as necessary to satisfy length requirements.

This will not give unique characters (e.g., 'aa11a' would be a possible output) -- which may or may not be what the OP wants. Also, the fact that you may need to run the function multiple times to get a string of the requested length means performance may not be spectacular, but if you're only calling this function once or twice, it won't matter. Here's a more complete implementation:

function randstr($len) {
  $currLen = 0;
  $value = '';
  while($currLen < $len) {
    $new = base_convert(rand(), 10, 36);
    $value .= $new;
    $currLen += strlen($new);
  }
  //$value may be longer than the requested $len
  return substr($value, 0, $len);
}

It's also worth noting that this string will be of less-than-perfect randomness -- the first char of each string output by base_convert will have a bias toward the lower end of the spectrum (as rand() will not completely fill a whole char's worth of bits every time). Ideally, you want a number of bits out of rand that will exactly fill some number of base-36 chars.

Using a source of entropy that gives you more bits than you need for the string in the first place (like /dev/urandom) would resolve this issue. But for most applications, the loss of entropy won't matter enough to justify the overhead of reading /dev/urandom.

Alternately, you could simply throw away the first char of each base_convert() call.


Here’s some example generator:

$length = 5;
$charset = '0123456789abcdefghijklmnopqrstuvwxyz';
$str = '';
while ($length--) {
    $str .= $charset[rand() % count($charset)];
}


Do you mean a random string?

If so, simply create a string containing the 36 characters, generate 5 random numbers and create the string based on the character positions (pseudo-code):

string src = "0123456789abcdefghijklmnopqrstuvwxyz"
string dst = ""
for i = 1 to 5:
    dst = dst + src[random(len(src))]

If you want 5 unique characters, you do the same thing but with one slight difference.

Generate the first random number in the range 0 through 35, the second in the range 0 through 34 and so on.

Then, as you add the character from the source string to your own string, replace the used character in the source string with the last character in the source string. This will prevent the same character from being selected twice:

string src = "0123456789abcdefghijklmnopqrstuvwxyz"
int srclen = len(src)
string dst = ""
for i = 1 to 5:
    idx = randon(len(src))
    dst = dst + src[idx]
    src[idx] = src[srclen-1]
    srclen = srclen - 1

Aside: @Tatu has provided a simple solution using str_shuffle which is a more elegant way of doing that last method (unique characters) but I'm not convinced it's the most efficient way since it's likely to involve a lot of swaps to get a decent shuffle. The method here seems to me to be more likely to be faster.

Keep that in mind if performance is important, but also keep in mind that I haven't tested how good it is - it may be fast enough - it may even blow my solution out of the water :-) As with all performance-related things, measure, don't guess.


http://php.net/manual/en/function.chr.php, in case you dislike hardcoding the alphabet.


Yet another approach, for funsies. Could be shortened - here it's a bit verbose, for readability.

function rand_string($length=5) {
    $values = str_split("abcdefghijklmnopqrstuvwxyz0123456789"));
    shuffle($values);
    $values = array_flip($values);

    $string = implode(array_rand($lenght));
    return $string;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消