2012-05-09 35 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