当然,如果我想要一个功能完全满足我的需求,我最好自己做。这是我想出来的。
//takes a string input, int length and optionally a string charset
//returns a hash 'length' digits long made up of characters a-z,A-Z,0-9 or those specified by charset
function custom_hash($input, $length, $charset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUFWXIZ'){
$output = '';
$input = md5($input); //this gives us a nice random hex string regardless of input
do{
foreach (str_split($input,8) as $chunk){
srand(hexdec($chunk));
$output .= substr($charset, rand(0,strlen($charset)), 1);
}
$input = md5($input);
} while(strlen($output) < $length);
return substr($output,0,$length);
}
这是一个非常通用的随机字符串发生器,但因为结果是由输入字符串和对输入的任何细微变化来确定会产生完全不同的结果它不只是任何旧的随机字符串发生器。你可以用这个做所有事情:
custom_hash('1d34ecc818c4d50e788f0e7a9fd33662', 16); // 9FezqfFBIjbEWOdR
custom_hash('Bilbo Baggins', 5, 'bcdfghjklmnpqrstvwxyz'); // lv4hb
custom_hash('', 100, '01');
// 1101011010110001100011111110100100101011001011010000101010010011000110000001010100111000100010101101
任何人都可以看到它的任何问题或任何改善的余地?
随着基64编码您将只能够输入减少到(4/8)/(6/8) - > 4/6〜66%的尺寸(这是假设你处理“丑陋的”base64字符而不添加任何新的)。我可能会考虑一种(二级)查找方法来获得真正的“漂亮”值。 – 2010-07-22 23:27:33
Re“所以我想我会想要不直接从十六进制转换为基数62的东西。” - 如果你想在URL安全字符串中编码16个字节,我的答案(22个字符)可能是最好的。你究竟在努力实现什么? – dkamins 2010-07-23 17:44:34