PHP中的短唯一ID [英] Short unique id in php

查看:122
本文介绍了PHP中的短唯一ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个唯一的ID,但是uniqid()给出了类似'492607b0ee414'的名称.我想要的是与tinyurl提供的类似的东西:'64k8ra'.越短越好.唯一的要求是,它不应具有明显的顺序,并且应该比看似随机的数字序列更漂亮.字母优先于数字,理想情况下,字母不能混合使用.由于条目数量不会那么多(最多10000个左右),因此发生碰撞的风险并不是一个很大的因素.

I want to create a unique id but uniqid() is giving something like '492607b0ee414'. What i would like is something similar to what tinyurl gives: '64k8ra'. The shorter, the better. The only requirements are that it should not have an obvious order and that it should look prettier than a seemingly random sequence of numbers. Letters are preferred over numbers and ideally it would not be mixed case. As the number of entries will not be that many (up to 10000 or so) the risk of collision isn't a huge factor.

任何建议表示赞赏.

推荐答案

制作一个小函数,该函数返回给定长度的随机字母:

Make a small function that returns random letters for a given length:

<?php
function generate_random_letters($length) {
    $random = '';
    for ($i = 0; $i < $length; $i++) {
        $random .= chr(rand(ord('a'), ord('z')));
    }
    return $random;
}

然后,您将使用伪代码调用该消息,直到它唯一为止,具体取决于存储该信息的位置:

Then you'll want to call that until it's unique, in pseudo-code depending on where you'd store that information:

do {
    $unique = generate_random_letters(6);
} while (is_in_table($unique));
add_to_table($unique);

您可能还想确保字母在词典中不构成单词.可能是整个英语词典,或者只是一个坏词词典,以避免客户发现不良品味.

You might also want to make sure the letters do not form a word in a dictionnary. May it be the whole english dictionnary or just a bad-word dictionnary to avoid things a customer would find of bad-taste.

如果您打算使用它,但它不是用于大量物品的话,那么我也将添加此选项才有意义,因为随着碰撞次数的增加,它可能会变得非常缓慢(获取表中已有的ID) .当然,您需要索引表,并且需要调整ID中的字母数以避免冲突.在这种情况下,如果有6个字母,您将有26 ^ 6 = 308915776个可能的唯一ID(减去错误词),足以满足您的10000个需求.

I would also add this only make sense if, as you intend to use it, it's not for a big amount of items because this could get pretty slow the more collisions you get (getting an ID already in the table). Of course, you'll want an indexed table and you'll want to tweak the number of letters in the ID to avoid collision. In this case, with 6 letters, you'd have 26^6 = 308915776 possible unique IDs (minus bad words) which should be enough for your need of 10000.

如果您想要字母和数字的组合,则可以使用以下代码:

If you want a combinations of letters and numbers you can use the following code:

$random .= rand(0, 1) ? rand(0, 9) : chr(rand(ord('a'), ord('z')));

这篇关于PHP中的短唯一ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆