2012-05-09 84 views
1

我正在玩Twitter API。一些數字(如Twitter的ID)是非常大的,如199693823725682700.PHP - 字符串到64位數

我有這個數字作爲字符串格式,現在我需要將它更改爲正常的可讀數,而不是像1000xE09,因爲我需要減少-1表示該字符串的數字。然後,我還需要以字符串形式發送該號碼。

總之,在PHP中,如何將字符串的數字(例如「199693823725682700」)更改爲另一個字符串「199693823725682699」(原始數字-1)?

非常感謝!

回答

4

如果BCMath不可用(這將是優選的選項,如果它是可用的),該功能將存儲遞減作爲字符串的任意大小的整數。沒有對浮點數或科學記數法插值的處理,它只能使用帶有可選符號的十進制數字串。

function decrement_string ($str) { 

    // 1 and 0 are special cases with this method 
    if ($str == 1 || $str == 0) return (string) ($str - 1); 

    // Determine if number is negative 
    $negative = $str[0] == '-'; 

    // Strip sign and leading zeros 
    $str = ltrim($str, '0-+'); 

    // Loop characters backwards 
    for ($i = strlen($str) - 1; $i >= 0; $i--) { 

    if ($negative) { // Handle negative numbers 

     if ($str[$i] < 9) { 
     $str[$i] = $str[$i] + 1; 
     break; 
     } else { 
     $str[$i] = 0; 
     } 

    } else { // Handle positive numbers 

     if ($str[$i]) { 
     $str[$i] = $str[$i] - 1; 
     break; 
     } else { 
     $str[$i] = 9; 
     } 

    } 

    } 

    return ($negative ? '-' : '').ltrim($str, '0'); 

} 

See it working

+0

這對我有用。 bssub和其他人不適合我的情況。非常感謝這樣聰明的代碼。 – clerksx

1

顯然現在只有在php中處理大整數的方法是使用bcmath擴展名。 PHP6中規劃了64位整數。

+0

將不會有PHP6。請參閱5.4發行說明。 – DmitryR

+0

@DmitryR:你有鏈接嗎?我在[5.4.0發佈公告](http://php.net/releases/5_4_0.php)中看到的唯一一件事是「PHP 5.4將是支持Windows XP和Windows 2003的最後一個系列。我們不會提供這些Windows版本在PHP 5.4之後的二進制包「。 – Travesty3