开发者

Create unique alpha numeric string for an input string/url?

开发者 https://www.devze.com 2022-12-08 20:11 出处:网络
I want to create a less than or equal to 10 character unique string for an input string which c开发者_如何学编程ould be a url

I want to create a less than or equal to 10 character unique string for an input string which c开发者_如何学编程ould be a url

http://stackoverflow.com/questions/ask

OR an alpha numeric string

programming124

but the result should be unique for every input...Is their any function or class that you use for your projects in php... Thanks...


If you want a unique and random string, you can use the following function to create a random string:

function randString($length) {
    $charset = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
    $str = '';
    while ($length-- > 0) {
        $str .= $charset[rand() % 62];
    }
    return $str;
}

After you have generated a new string, look up your database if that string already exists. If so, repeat that step until you’ve generated a unique string. Then store that new string in the database:

do {
    $randString = randString(10);
    // look up your database if $randString already exists and store the result in $exists
} while ($exists);
// store new random string in database


The simplest function available in php is uniqid. It is a little longer that you had mentioned, and wont work well with load balancing, but if you are doing something super simple, it should work alright.

0

精彩评论

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

关注公众号