注意:回答这个是因为标题,将电话号码视为整数不是一个好主意
您应该利用 PHP 的类型处理功能并在电话号码上使用字符串函数,但如果您想使用 C 风格并保持使用整数你有:
-
division 的
/ 运算符,有助于获取第一个数字(将123 划分为100 会给你第一个数字,但不正确因为123/100=1.23,使用floor() 函数会给你floor(123/100)=1 但我们可能在这里遇到问题,因为floor() 的结果是float 类型而不是integer)
-
modulo 的
% 运算符,有助于获取最后一位数字(123 modulo 10 将立即为您提供最后一位数字和类型整数,例如123%10=3)
所以你可以像这样(整数方式)从你的电话号码中提取所需的部分:
$last=$no%100000; // get last 5 digits (modulo by 1 followed by 5 zeroes)
$no=$no-$last; // subtract the last digits from original number
$no=$no/100000; // divide to shorten the number, end up with a natural number
$area=$no%1000; // get last 3 again
$prefix=($no-$area)/1000; //remainder is the first digits of the original number
或(float/double/real 方式)- 更具可读性:
$last=$no%1e5; // scientific notation 1e5 = 10000 (1 followed by 5 zeroes)
$no=($no-$last)/1e5;
$area=$no%1e3;
$prefix=($no-$area)/1e3;
直播代码:http://codepad.viper-7.com/tVRjXC
注意:科学计数法e使用类型float
您还应该记住,32 位平台上的最大整数是2^31 = 2.147.483.648
现在,将此代码与
0077705501234 之类的“电话号码”一起使用会让您头疼!
所以它来自数据库,但如果有任何更改,它会显示为真正的int PHP 将解释 octal base 中的任何 0 前导数字并在内部将其转换为十进制所以你最终会得到一个完全不同的“电话号码”,确切地说是垃圾。
如果 PHP 将它作为 string 接收,并且您真的想使用整数,您可以使用 type-cast 使用 (int) $no 或使用 $no+0 等进行转换。
无论如何,前导零对整数无关紧要,但对于字符串则如此,因此您最终可能会得到 77705501234 并且您可能想要进行长度检查(integer 浮点方式):
我要使用浮点数,因为有很多零需要依靠......
我们知道该号码必须包含 13 数字,因此我们可以检查 if ( $no > 1e12 ) 并且可能还检查 if ( $no < 1e14 ) 以进行验证。
如果你还想知道数字的“长度”(你需要知道pow()):
for ($i=1;$i<13;$i++) { //count from 1 to 12
//stop when $no modulo 10^$i is the number
if ( $no % pow(10,$i) == $no ) break;
}
// number of digits of $no are stored in $i - equivalent to strlen()
最后,即使缺少前导零整数,也能正确打印您的号码:
printf('Your number: (%05u) %03u - %05u',$prefix,$area,$last);
直播代码:http://codepad.viper-7.com/Xgr8RQ
旁注:对于大数字,您也有 BCMath 函数,但它们适用于字符串