douyonglang4845 2014-09-01 13:56
浏览 95
已采纳

如何生成只有7个字符的UID并排除重复,如imgur.com

take a look at this URL: http://imgur.com/JLhIuYt

You will see that the URL has a seemingly random string generated, which is build from 7 characters of

  1. small letters (26 characters)
  2. big letters (26 characters)
  3. numbers (10 numbers)

n = (26+26+10) = 62

I would like to know how it is possible to generate a random string of only 7 characters, that works as a GUID.

With only 7 characters, imgur is using, they can generate 3.521.614.606.208 variations (62 to the power of 7). The question now arises, how imgur handles each variation to be used as an identifier, since it seems that those numbers are generated randomly.

Is there a way to find out, how it is possible to use 7 characters as UID and making sure, they don't repeat themselves?

One solution could be, to generate them in chunks and to use one after the other. Seems rather not good.

Any kind appreciated!

Btw. Random Strin best generated in PHP

  • 写回答

2条回答 默认 最新

  • doulian7305 2014-09-01 14:13
    关注

    You can use this one-liner to generate a random string:

    substr(
        str_shuffle(
            str_repeat('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890', 7)
        ), 
        0, 
        7
    )
    

    Then, you can check in a database if it's already used or not like this for example:

    while(
        existsInTheDB(
            $str = substr(
                str_shuffle(
                    str_repeat(
                        'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890',
                        7
                    )
                ), 
                0, 
                7
            )
        )
    ){}
    
    //now you can use $str
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?