php - 将可变长度 URL 映射到数字 (0...3) 的简单哈希函数

标签 php algorithm hash

我的网站使用来自单个域的各种资源,例如:

http://static.example.com/javascript/common.js
http://static.example.com/javascript/common.css
http://static.example.com/javascript/menu/menu.js
http://static.example.com/javascript/menu/menu.css
http://static.example.com/images/1804/logo/02000100.jpg
http://static.example.com/images/1804/headers/main/09400060.png
http://static.example.com/images/1804/headers/home/1101/06900200-01.jpg
http://static.example.com/images/1804/headers/home/1101/06900200-02.jpg

我需要一个非常简单的字符串哈希函数,将这些 URL 映射到数字,数字为 0、1、2 和 3。该算法应该是确定性和统一的。我已经标记了问题 PHP,但可以接受通用答案。

您可能已经猜到我为什么需要这个;我打算将 URL 更改为,例如:

http://0.static.example.com/javascript/common.js
http://2.static.example.com/javascript/common.css

最佳答案

我更喜欢对字符串进行 crc32 哈希处理,然后将其与极限值取模。

代码:

function numeric_hash($str, $range) {
    return sprintf("%u", crc32($str)) % $range;
}

用法:

$str = "http://static.example.com/javascript/common.js
http://static.example.com/javascript/common.css
http://static.example.com/javascript/menu/menu.js
http://static.example.com/javascript/menu/menu.css
http://static.example.com/images/1804/logo/02000100.jpg
http://static.example.com/images/1804/headers/main/09400060.png
http://static.example.com/images/1804/headers/home/1101/06900200-01.jpg
http://static.example.com/images/1804/headers/home/1101/06900200-02.jpg";
$urls = explode("\n", $str);

foreach($urls as $url) {
    echo numeric_hash($url, 4) . "\n";
}

输出:

1
3
3
3
1
3
1
3

关于php - 将可变长度 URL 映射到数字 (0...3) 的简单哈希函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13414612/

相关文章:

php - YII 在 REST GET 请求中获取请求体

php - 如何使用复选框将 $1.00 添加到 $amount

php - 发送电子邮件 navigator.useragent

.net - 在每个文件的 list 中哪里可以看到哈希值?

ruby - 无法理解 ruby​​ 如何打印此哈希

PHP GD : Bad quality on resize?

algorithm - 计算在基于瓦片的游戏中哪些瓦片被点亮 ("raytracing")

database - 有什么方法可以将图形存储在数据库中以使其易于遍历?

java - 给定一个大树结构,是否有一种有效的算法来对树进行查询或过滤?

security - 加密和哈希之间的区别