单行 PHP 随机字符串生成器?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19017694/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 18:40:25  来源:igfitidea点击:

One-line PHP random string generator?

phprandom

提问by David Garcia

I am looking for the shortest way to generate random/unique strings and for that I was using the following two:

我正在寻找生成随机/唯一字符串的最短方法,为此我使用了以下两个:

$cClass = sha1(time());

or

或者

$cClass = md5(time());

However, I need the string to begin with an an alphabet character, I was looking at base64 encoding but that adds ==at the end and then I would need to get rid of that.

但是,我需要字符串以字母字符开头,我正在查看 base64 编码,但==在末尾添加,然后我需要摆脱它。

What would be the best way to achieve this with one line of code?

用一行代码实现这一目标的最佳方法是什么?



Update:

更新:

PRNDL came up with a good suggestions wich I ended up using it but a bit modified

PRNDL 提出了一个很好的建议,我最终使用了它,但做了一些修改

echo substr(str_shuffle(abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ),0, 1) . substr(str_shuffle(aBcEeFgHiJkLmNoPqRstUvWxYz0123456789),0, 31)

Would yield 32 characters mimicking the md5 hash but it would always product the first char an alphabet letter, like so;

会产生 32 个模仿 md5 哈希的字符,但它总是将第一个字符产生一个字母,就像这样;

solution 1

解决方案1

However, Uoursreally improved upon and his answer;

然而,Uours确实改进了他的回答;

substr(str_shuffle("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 1).substr(md5(time()),1);

is shorter and sweeter

更短更甜

The other suggestion by Anonymous2011was very awesome but the first character for some reason would always either M, N, Y, Z so didnt fit my purposes but would have been the chosen answer, btw does anyone know why it would always yield those particular letters?

Anonymous2011的另一个建议非常棒,但出于某种原因,第一个字符总是 M、N、Y、Z,所以不符合我的目的,但会是选择的答案,顺便说一句,有人知道为什么它总是会产生那些特定的字母?

Here is the preview of my modified version

这是我修改后的版本的预览

echo  rtrim(base64_encode(md5(microtime())),"=");

runner up

亚军

采纳答案by Uours

Rather than shuffling the alphabet string , it is quicker to get a single random char .

Get a single random char from the string and then append the md5( time( ) )to it . Before appending md5( time( ) )remove one char from it so as to keep the resulting string length to 32 chars :

与打乱字母表字符串相比,获得单个随机字符会更快。

从字符串中获取一个随机字符,然后将 附加md5( time( ) )到它。在追加之前md5( time( ) )从中删除一个字符,以便将结果字符串长度保持为 32 个字符:

substr("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", mt_rand(0, 51), 1).substr(md5(time()), 1);

Lowercase version :

小写版本:

substr("abcdefghijklmnopqrstuvwxyz", mt_rand(0, 25), 1).substr(md5(time()), 1);

Or even shorter and a tiny bit faster lowercase version :

或者甚至更短、更快一点的小写版本:

chr(mt_rand(97, 122)).substr(md5(time()), 1);

/* or */

chr(mt_rand(ord('a'), ord('z'))).substr(md5(time()), 1);


A note to anyone trying to generate many random strings within a second:
Since
time( )returns time in seconds ,md5( time( ) )will be same throughout a given second-of-time due to which if many random strings were generated within a second-of-time, those probably could end up having some duplicates .


任何试图在一秒钟内生成许多随机字符串的人的注意事项:
由于
time( )以秒为单位返回时间,md5( time( ) )因此在给定的第二时间中将相同,因此如果在第二时间内生成了许多随机字符串,那些可能最终可能会有一些重复。


I have tested using below code . This tests lower case version :


我已经使用下面的代码进行了测试。这测试小写版本:

    $num_of_tests = 100000;

    $correct = $incorrect = 0;

    for( $i = 0; $i < $num_of_tests; $i++ )
    {
        $rand_str = substr( "abcdefghijklmnopqrstuvwxyz" ,mt_rand( 0 ,25 ) ,1 ) .substr( md5( time( ) ) ,1 );

        $first_char_of_rand_str = substr( $rand_str ,0 ,1 );

        if( ord( $first_char_of_rand_str ) < ord( 'a' ) or ord( $first_char_of_rand_str ) > ord( 'z' ) )
        {
            $incorrect++;
            echo $rand_str ,'<br>';
        }
        else
        {
            $correct++;
        }
    }

    echo 'Correct: ' ,$correct ,' . Incorrect: ' ,$incorrect ,' . Total: ' ,( $correct + $incorrect );

回答by 23kulpamens

I had found something like this:

我发现了这样的东西:

$length = 10;
$randomString = substr(str_shuffle(md5(time())),0,$length);
echo $randomString;

回答by PRNDL Development Studios

If you need it to start with a letter, you could do this. It's messy... but it's one line.

如果你需要它以字母开头,你可以这样做。它很乱……但它是一行。

$randomString = substr(str_shuffle("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 1) . substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 10);

echo $randomString;

回答by maaarghk

I decided this question needs a better answer. Like code golf! This also uses a better random byte generator.

我决定这个问题需要一个更好的答案。喜欢代码高尔夫!这也使用了更好的随机字节生成器。

preg_replace("/[\/=+]/", "", base64_encode(openssl_random_pseudo_bytes(8)));

Increase the number of bytes for a longer password, obviously.

显然,为更长的密码增加字节数。

回答by Rudie

Creates a 200 char long hexdec string:

创建一个 200 个字符长的十六进制字符串:

$string = bin2hex(openssl_random_pseudo_bytes(100));

maaarghk's answeris better though.

不过,maaarghk 的回答更好。

回答by Daniel Reyes

base_convert(microtime(true), 10, 36);

base_convert(microtime(true), 10, 36);

回答by Saud Khan

You can try this:

你可以试试这个:

 function KeyGenerator($uid) {
    $tmp = '';
    for($z=0;$z<5;$z++) {
      $tmp .= chr(rand(97,122)) . rand(0,100);
    }
    $tmp .= $uid;
    return $tmp;
  }

回答by RobAtStackOverflow

I have generated this code for you. Simple, short and (resonably) elegant.

我已经为你生成了这个代码。简单,简短且(相当)优雅。

This uses the base64 as you mentioned, if length is not important to you - However it removes the "==" using str_replace.

如果长度对您不重要,它会使用您提到的 base64 - 但是它会使用 str_replace 删除“==”。

<?php
        echo  str_ireplace("==", "", base64_encode(time()));
?>

回答by Emilio Gort

I use this function

我用这个功能

usage:

用法:

 echo randomString(20, TRUE, TRUE, FALSE);

  /**
   * Generate Random String
   * @param Int Length of string(50)
   * @param Bool Upper Case(True,False)
   * @param Bool Numbers(True,False)
   * @param Bool Special Chars(True,False)
   * @return String  Random String
   */
  function randomString($length, $uc, $n, $sc) {
      $rstr='';
      $source = 'abcdefghijklmnopqrstuvwxyz';
      if ($uc)
          $source .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
      if ($n)
          $source .= '1234567890';
      if ($sc)
          $source .= '|@#~$%()=^*+[]{}-_';
      if ($length > 0) {
          $rstr = "";
          $length1= $length-1;
          $input=array('a','b','c','d','e','f','g','h','i','j,''k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z')  
          $rand = array_rand($input, 1)
          $source = str_split($source, 1);
          for ($i = 1; $i <= $length1; $i++) {
              $num = mt_rand(1, count($source));
              $rstr1 .= $source[$num - 1];
              $rstr = "{$rand}{$rstr1}";
          }
      }
      return $rstr;
  }

回答by user985366

It really depends on your requirements.

这真的取决于你的要求。

I needed strings to be unique between test runs, but not many other restrictions.

我需要字符串在测试运行之间是唯一的,但没有太多其他限制。

I also needed my string to start with a character, and this was good enough for my purpose.

我还需要我的字符串以一个字符开头,这对我的目的来说已经足够了。

$mystring = "/a" . microtime(true);

$mystring = "/a" . microtime(true);

Example output:

示例输出:

a1511953584.0997

a1511953584.0997