當然,如果我想要一個功能完全滿足我的需求,我最好自己做。這是我想出來的。
//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