开发者

Best way to generate 6char UP/down string? PHP

I know this question is incredibly common, but I'm asking the following (Google yields no results, and the other question which was similar to mine had incorrect source :s):

What would be the best way to get a random 6 character different cased alphabet string eg 'aWGuPk'/'pZyTFu' or something of the sort (in PHP)? By 'best', the function w开发者_StackOverflowith the shortest amount of code and most the most efficient?

Sorry if this might be a duplicate of something I can't find on SO.

Thanks, Karan


This is the function I use (I must have cut and paste this from somewhere on the internet, can't remember where!):-

function createRandomString($len=10) {
    $chars = "abcdefghijkmnopqrstuvwxyz023456789";
    srand((double)microtime()*1000000);
    $i = 0;
    $pass = '' ;
    while ($i <= $len) {
        $num = rand() % 33;
        $tmp = substr($chars, $num, 1);
        $pass = $pass . $tmp;
        $i++;
    }
    return $pass;
}

usage:-

$myStr = createRandomString(6);

Add in uppercase characters to $chars if you want mixed case


Personally, I'd create an array of allowable characters and use array_rand to append them to a string the required number of times:

// str_split requires PHP5
$chars = str_split('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');
for ($i = 0, $str = ''; $i < 6; ++$i) {
    $str .= $chars[array_rand($chars)];
}

Incidentally, when generating random strings that will be shown to a user, I tend to remove vowels from the list of chars to avoid accidentally generating offensive words.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜