One-line PHP random string generator?

2019-01-31 03:07发布

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.

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

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;

solution 1

However, Uours really improved upon and his answer;

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

is shorter and sweeter

The other suggestion by Anonymous2011 was 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?

Here is the preview of my modified version

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

runner up

标签: php random
16条回答
祖国的老花朵
2楼-- · 2019-01-31 03:35

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.

查看更多
趁早两清
3楼-- · 2019-01-31 03:35

This function returns random lowercase string:

function randomstring($len=10){
 $randstr='';
 for($iii=1; $iii<=$len; $iii++){$randstr.=chr(rand(97,122));};
 return($randstr);
};
查看更多
再贱就再见
4楼-- · 2019-01-31 03:39

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;
查看更多
太酷不给撩
5楼-- · 2019-01-31 03:40

to generate strings consists of random characters, you can use this function

public function generate_random_name_for_file($length=50){
    $key = '';
    $keys = array_merge(range(0, 9), range('a', 'z'));
    for ($i = 0; $i < $length; $i++) {
        $key .= $keys[array_rand($keys)];
    }
    return $key;
}
查看更多
登录 后发表回答