How to generate random numbers/letters with PHP/Ja

2019-09-21 10:06发布

问题:

I have looked all over but I can't find it. I need a script to generator random captial letters and numbers at the click of a button. I need to have the dash " - " between every 4 characters. Can anyone point me in the right direction or know how to do this? Thanks!

回答1:

There are many ways to generate random 'things':

  1. rand function
  2. microtime function
  3. uniqid function

Then if you need letters and number you can use md5 function to generate a hash from one of the above.

You can then change the md5 hash to upper case and get what you want (lenght) and insert '-' for every 4 characters.



回答2:

//generate 4 characters random string
 function generateRandomString($length = 4, $letters = '1234567890QWERTYUIOPASDFGHJKLZXCVBNM'){
    $s = '';
    $lettersLength = strlen($letters)-1;

    for($i = 0 ; $i < $length ; $i++)
    {
        $s .= $letters[rand(0,$lettersLength)];
    }

    return $s;
} 

echo generateRandomString()."-".generateRandomString();

Fastest way. Function can be improved though... write it at hand, right now. :)