Php 用于将可变长度URL映射到数字(0…3)的简单哈希函数
我的网站使用单个域中的各种资源,例如:Php 用于将可变长度URL映射到数字(0…3)的简单哈希函数,php,algorithm,hash,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/1
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
http://0.static.example.com/javascript/common.js
http://2.static.example.com/javascript/common.css
我需要一个非常简单的字符串哈希函数,将这些URL映射到数字,数字是0、1、2和3。算法应具有确定性和统一性。我已经将问题标记为PHP,但一般答案是可以接受的
你可能已经猜到我为什么需要这个了;我计划将URL更改为,例如:
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
http://0.static.example.com/javascript/common.js
http://2.static.example.com/javascript/common.css
如果你有很多URL,你应该只进行一次强散列,然后使用
mod
如果您的URL很少,或者大小或调用频率不均匀,“随机”分布可能不好,您应该创建四个列表,然后静态地将URL分配给每个列表,可以手动分配,也可以根据每个URL的请求数使用一些启发式方法。我更喜欢对字符串进行
crc32
散列,取它的模和极限
代码:
用法:
$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
我想说的是strlen($str)%$num。。。它肯定很快:)是的,很快,但不是统一的。。。查看包含单词标题的URL?我会在一个页面上放置大约15个这样20个URL中的15个会有hash=3。是的,这更适用于更人性化的图像名称:)hexdec有什么用?我从你的示例代码中得到负数,顺便说一句,这不是问题。@SalmanA,哎呀,我想
crc32
返回一个十六进制值。你必须在32位php上,函数可以根据。我相信用abs()。