-2

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!

Jonathon Reinhart
  • 132,704
  • 33
  • 254
  • 328
user2817557
  • 9
  • 1
  • 1
  • 3
    Questions asking for code must **demonstrate a minimal understanding of the problem being solved**. Include attempted solutions, why they didn't work, and the *expected* results. See also: [Stack Overflow question checklist](http://meta.stackexchange.com/questions/156810/stack-overflow-question-checklist) – Danny Beckett Sep 26 '13 at 01:30
  • http://stackoverflow.com/questions/1349404/generate-a-string-of-5-random-characters-in-javascript – Jonathon Reinhart Sep 26 '13 at 01:33

2 Answers2

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.

David Lin
  • 13,168
  • 5
  • 46
  • 46
1
//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. :)

Adrian P.
  • 5,060
  • 2
  • 46
  • 47
  • Thank you adrian! How do I insert that into HTML? – user2817557 Sep 26 '13 at 02:05
  • @user2817557: this is PHP, not JavaScript (that's for the ` – Qantas 94 Heavy Sep 26 '13 at 02:10
  • Ty Qantas, it worked. But how do I increase the length of the generated string? About 20 characters, NEVERMIND SOLVED. – user2817557 Sep 26 '13 at 02:24
  • Javascript solution: http://stackoverflow.com/questions/1349404/generate-a-string-of-5-random-characters-in-javascript – Adrian P. Oct 01 '13 at 12:53