我需要PHP函数,它将从任何输入字符串创建8个字符长[a-z]哈希值。 所以例如当我提交“Stack Overflow”时,它将返回例如“gdqreaxc”(8个字符[a-z]不允许数字)
答案 0 :(得分:11)
也许是这样的:
$hash = substr(strtolower(preg_replace('/[0-9_\/]+/','',base64_encode(sha1($input)))),0,8);
这会生成一个SHA1哈希值,base-64对它进行编码(给我们提供完整的字母表),删除非alpha字符,对其进行小写并截断它。
$input = 'yar!';
:
mwinzewn
$input = 'yar!!';
:
yzzhzwjj
所以传播似乎很好。
答案 1 :(得分:3)
此函数将生成包含均匀分布的字符[a-z]
:
function my_hash($string, $length = 8) {
// Convert to a string which may contain only characters [0-9a-p]
$hash = base_convert(md5($string), 16, 26);
// Get part of the string
$hash = substr($hash, -$length);
// In rare cases it will be too short, add zeroes
$hash = str_pad($hash, $length, '0', STR_PAD_LEFT);
// Convert character set from [0-9a-p] to [a-z]
$hash = strtr($hash, '0123456789', 'qrstuvwxyz');
return $hash;
}
顺便说一下,如果这对你来说很重要,对于100,000个不同的字符串,你将有大约2%的哈希冲突几率(对于8个字符长的哈希),对于一百万个字符串,这个机会上升到〜 90%,如果我的数学是正确的。
答案 2 :(得分:0)
function md5toabc($myMD5)
{
$newString = "";
for ($i = 0; $i < 16; $i+=2)
{
//add the first val of 0-15 to the second val of 0-15 for a range of 0-30
$myintval = hexdec(substr($myMD5, $i, $i +1) ) +
hexdec(substr($myMD5, $i+1, $i +2) );
// mod by 26 and add 97 to get to the lowercase ascii range
$newString .= chr(($myintval%26) + 97);
}
return $newString;
}
请注意,这会引入各种角色的偏见,但会按照您的意愿行事。 (就像当你掷两个骰子时,最常见的值是7合并......)加上模数等......
答案 3 :(得分:0)
通过使用和修改一个众所周知的算法(输出),你可以给你一个好的a-p {8}(但不是a-z):
function mini_hash( $string )
{
$h = hash( 'crc32' , $string );
for($i=0;$i<8;$i++) {
$h{$i} = chr(96+hexdec($h{$i}));
}
return $h;
}
你在那里张贴的一系列有趣的约束
答案 4 :(得分:-1)
怎么样
substr (preg_replace(md5($mystring), "/[1-9]/", ""), 0, 8 );
你可以通过
添加更多的熵preg_replace($myString, "1", "g");
preg_replace($myString, "2", "h");
preg_replace($myString, "3", "i");
等而不是剥离数字。