簡體   English   中英

字符串中的唯一編號 - php

[英]unique number from a string - php

我有一些包含字母數字值的字符串,比如說

asdf1234 ,

qwerty//2345

ETC..

我想生成一個與字符串相關的特定常數。 該數字不應與生成的與其他字符串相對應的任何數字匹配。

它必須是一個數字嗎?

您可以簡單地 hash 字符串,這將為您提供唯一值。

echo md5('any string in here');

注意:這是一個單向 hash,它不能從 hash 轉換回字符串。

這就是密碼的典型存儲方式(使用這個或另一個 hash function,通常添加“鹽”方法。)然后通過對輸入進行哈希處理並與存儲的 Z0800FC577294C335904B22 進行比較來檢查密碼。

編輯:md5 散列長度為 32 個字符。

看看其他 hash 功能:
http://us3.php.net/manual/en/function.crc32.php (返回一個數字,可能是負數)
http://us3.php.net/manual/en/function.sha1.php (40 個字符)

您可以使用像md5這樣的散列 function ,但這不是很有趣。

相反,您可以將字符串轉換為其 ASCII 字符序列(因為您說它是字母數字) - 這樣,它可以很容易地轉換回來,對應於字符串的長度(確切地說是長度 *3),它有0 碰撞機會,因為它只是將其轉換為另一種表示形式,總是一個數字,而且更有趣......示例代碼:

function encode($string) {
    $ans = array();
    $string = str_split($string);
    #go through every character, changing it to its ASCII value
    for ($i = 0; $i < count($string); $i++) {

        #ord turns a character into its ASCII values
        $ascii = (string) ord($string[$i]);

        #make sure it's 3 characters long
        if (strlen($ascii) < 3)
            $ascii = '0'.$ascii;
        $ans[] = $ascii;
    }

    #turn it into a string
    return implode('', $ans);
}

function decode($string) {
    $ans = '';
    $string = str_split($string);
    $chars = array();

    #construct the characters by going over the three numbers
    for ($i = 0; $i < count($string); $i+=3)
        $chars[] = $string[$i] . $string[$i+1] . $string[$i+2];

    #chr turns a single integer into its ASCII value
    for ($i = 0; $i < count($chars); $i++)
        $ans .= chr($chars[$i]);

    return $ans;
}

例子:

$original = 'asdf1234';

#will echo
#097115100102049050051052
$encoded = encode($original);
echo $encoded . "\n";

#will echo asdf1234
$decoded = decode($encoded);
echo $decoded . "\n";

echo $original === $decoded; #echoes 1, meaning true

您正在尋找 hash function,例如md5 您可能希望將 $raw_output=true 參數傳遞給它以訪問原始字節,然后將它們轉換為您想要的數字的任何表示形式。

加密 hash function 將為每個輸入字符串提供不同的數字,但它是一個相當大的數字 - 例如,在 SHA-1 的情況下為 20 個字節。 原則上,兩個字符串有可能產生相同的 hash 值,但發生的機會非常小,可以忽略不計。

如果你想要一個更小的數字——比如說,一個 32 位的 integer——那么你不能使用 hash function 因為碰撞的可能性太高了。 相反,您需要記錄您已建立的所有映射。 制作一個將字符串與數字相關聯的數據庫表,每次給定一個字符串時,在表中查找它。 如果您在那里找到它,請返回相關的號碼。 如果沒有,請選擇任何現有記錄都未使用的新數字,並將新字符串和數字添加到表中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM