PHP - 独特的哈希函数,只有 4 位数字(不需要精确)
我正在构建一个简单的 URL 缩短脚本,我想对 URL 进行哈希处理以用作唯一 id,但如果我使用 MD5 之类的东西,则 URL 不会很短。
他们是使用一些散列函数还是创建一个只有 4 或 5 位数字长的唯一 ID?
I'm building a simple URL shortening script, I want to hash the URL to serve as a unique id but if I used something like MD5 the URL wouldn't be very short.
Is their some hashing functions or anyway to create a unique ID thats only 4 or 5 digits long?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
使用自动递增整数并将它们转换为由所有字母(小写和大写)组成的标识符以缩短它们:
以及相应的函数将它们恢复为整数:
Use auto incrementing integers and convert them into identifiers consisting of all letters (lower & uppercase) to shorten them:
and the corresponding function to get them back to integers:
散列会导致冲突。只需使用自动递增值即可。这也包括使用字母数字字符来压缩它。这就是大多数 URL 缩短程序的工作原理。
尼克拉斯下面的回答做得非常好。
Hashing will cause collisions. Just use an autoincrementing value. This includes using alphanumeric characters too to compress it. That is how most URL shortners work.
niklas's answer below is wonderfully done.
使用 MD5(或等效方法)的优点是可能性的数量如此之大,以至于您可以出于所有实际目的假设该值是唯一的。为了确保 4 位随机 ID 是唯一的,需要一个数据库来跟踪现有 ID。
本质上,您必须重复生成 ID 并对照数据库进行检查。
The advantage of using MD5 (or equivalent methods) is that the number of possibilities is so large that you can, for all practical purposes, assume that the value is unique. To ensure that a 4-digit random-like ID is unique would require a database to track existing IDs.
Essentially you have to repeatedly generate IDs and check against the DB.
您始终可以只保留 MD5 的前 5 个字符,如果它已经存在,您可以向 url 字符串添加一个随机值,然后重试,直到获得唯一的值。
You could always just keep the first 5 characters of a MD5 and if it already exists you add a random value to the url-string and retry until you get a unique one.
我刚刚复制了代码并运行了它,看来他的字符串函数是向后的。我输入了短网址中生成的数字,然后回想了一下,得到了一个不同的数字。所以我解码了这个数字,发现该字符串必须与上面当前的编码相反地反馈到长网址中。
I just copied the code and ran it, and it appears that he string function are backwards. I entered the number generated in the shorturl and ran it back thought and got a different number. So I decoded the number and found the string has to be fed back into long url in reverse with the current coding above.