当然,如果我想要一个功能来完美地满足我的需求,我最好自己制作。这是我想出的。
//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 = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUFWXIZ0123456789'){
$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, '0123456789bcdfghjklmnpqrstvwxyz'); // lv4hb
custom_hash('', 100, '01');
// 1101011010110001100011111110100100101011001011010000101010010011000110000001010100111000100010101101
有人看到它有任何问题或有任何改进的余地吗?