使用PHP将随机文本转换为数字


Convert random text to a number with PHP

我需要将随机文本转换为数字。但是随机文本必须始终转换为相同的数字。例如:

xxxx -> 10
testing -> 396
stackoverflow -> 72

我无法使用字符数来转换string,因为如果我有两个具有相同编号characters的字符串,则它们需要具有不同的编号(至少在大多数情况下)。

我不需要这个数字在一个范围内。不它可以是任何数字,因为给定某个字符串,它总是相同的。

您可以尝试使用哈希(md5sha1等):

$number = hexdec( md5("hello world") );
$number = hexdec( sha1("hello world") );

相同字符串的哈希将转换为相同的数字。

关于;

$number = crc32($string);

应该是便宜的,提供整数输出,并为您的用例产生合理的随机性。

已经展示的其他方法有可能发生冲突。以下内容不应出现。

$num = "";
for($i = 0; $i < strlen($str); $i++)
    $num .= str_pad(ord($str[$i]), 3 "0", STR_PAD_LEFT);
return $num;