代码之家  ›  专栏  ›  技术社区  ›  jspeshu

如何在php中将字符串转换为唯一整数

php
  •  5
  • jspeshu  · 技术社区  · 15 年前

    如何将字符串(即电子邮件地址)转换为唯一整数,以将其用作ID。

    7 回复  |  直到 13 年前
        1
  •  7
  •   NikiC    15 年前

    PHP整数可以存储的信息量是有限的。您可以在字符串中存储的信息量不是(至少在字符串不太长的情况下)

    不可能的 没有数据丢失。

    您可以使用哈希算法,但哈希算法可能总是有冲突。特别是如果你想把一个字符串散列成一个整数,那么冲突概率是相当高的——整数只能存储很少的数据。

        2
  •  5
  •   Preet Sangha    15 年前

    试试 binhex 功能

    从上述站点:

    <?php
    $str = "Hello world!";
    echo bin2hex($str) . "<br />";
    echo pack("H*",bin2hex($str)) . "<br />";
    ?>
    

    输出

    48656c6c6f20776f726c6421
    Hello world!
    
        3
  •  2
  •   Spudley Pat    15 年前

        4
  •  2
  •   Waqar Alamgir    11 年前

    这段代码生成64位数字,可以用作它,也可以用作MySQL等数据库的bigInt/类似数据类型。

    function get64BitNumber($str)
    {
        return gmp_strval(gmp_init(substr(md5($str), 0, 16), 16), 10);
    }
    
    echo get64BitNumber('Hello World!'); // 17079728445181560374
    echo get64BitNumber('Hello World#'); // 2208921763183434891
    echo get64BitNumber('http://waqaralamgir.tk/'); // 12007604953204508983
    echo get64BitNumber('12345678910'); // 4841164765122470932
    
        5
  •  0
  •   adamnfish    15 年前

    如果电子邮件是ascii文本,则可以使用PHP ord function 生成一个唯一的整数,但它将是一个非常大的数字!

    考虑一下“abc”。

    ord("a");
    >> 97
    
    ord("b");
    >> 98
    
    ord("c");
    >> 99
    

    用0填充这些数字,就可以得到一个唯一的数字,即: 970980990 .

    我希望这能有帮助!

        6
  •  0
  •   SnakeMaster    6 年前

    你可以用 crc32 功能。

    $email = "user@gmail.com";
    echo $email . " = " . crc32($email);
    

    实例: https://repl.it/repls/HonorableRespectfulBundledsoftware

        7
  •  -1
  •   Slavic    15 年前

    为什么不在本地创建自己的关联表,用唯一的整数绑定电子邮件?

    因此,工作流程如下:

    1   get the record from the ldap server. 
    2   check it locally if it has already an int assigned.
    2.1 if yes use that int.
    2.2 if no, generate an associative row in the table locally.
    3   do your things with the unique ids.
    

        8
  •  -1
  •   xoza    13 年前

    您可以使用此功能:

    function stringToInteger($string) {
        $output = '';
        for ($i = 0; $i < strlen($string); $i++) {
            $output .= (string) ord($string[$i]);
        }
        return (int) $output;
    }
    

    推荐文章