我有字母数字字符串值。我需要用一个整数值来表示每个字符串。
结果整数必须介于30和150之间。
多个字符串可以具有相同的整数值
在每次运行中,特定字符串必须给出相同的整数值
加密并不重要,字符串值也没有价值
优选更快的计算
所有整数都不能有相同的值。
编辑:我试过intval()
,但它给了我零。然后我尝试了md5
和sha1
,它们给了我很长的字符串。我试过base_convert
,但没能成功。
这需要一个散列函数。你的范围是150-30=120
,所以你需要对结果取120(% 120
(的模,然后加30。
在PHP中,大多数标准哈希函数(md5,sha(都是出于安全目的,并返回一个不太有用的字符串。在这种情况下,您可以使用循环冗余检查:http://php.net/crc32.这不是一个散列(值不是均匀分布的(,但可能足够接近您的目的。
$stringhash = crc32($string) % 120 + 30;
如果你需要一个更均匀的分布,你也可以使用一个简单的标准散列,例如md5,但速度较慢。
// Take the first 8 alphanumeric digits of the hash (= 32 bits) because we want to keep an int and not convert it to a floating point
$stringhash = intval(substr(md5($string), 0, 8), 16) % 120 + 30;
通过使用@dtech的答案,我完成了如下函数:
public function convertStringToInteger($string, $min, $max, $dateDepended=FALSE) {
$interval = $max-$min;
if ($dateDepended) {
$addMore=strtotime("today");
} else {
$addMore=0;
}
return ( (crc32($string)+$addMore) % $interval ) + $min;
}
convertStringToInteger("myword",30,150,TRUE);