使用PHP,将“123”这样的字符串转换为整数的最快方法是什么?

为什么这种方法是最快的?如果它得到意外的输入,比如“hello”或数组,会发生什么?


当前回答

从任意字符串中提取的整数

$in = 'tel.123-12-33';

preg_match_all('!\d+!', $in, $matches);
$out =  (int)implode('', $matches[0]);

/ /美元= ' 1231233 ';

其他回答

$int = settype("100", "integer"); //convert the numeric string to int

从任意字符串中提取的整数

$in = 'tel.123-12-33';

preg_match_all('!\d+!', $in, $matches);
$out =  (int)implode('', $matches[0]);

/ /美元= ' 1231233 ';

我个人觉得选角是最漂亮的。

$iSomeVar = (int) $sSomeOtherVar;

如果发送了'Hello'这样的字符串,它将被转换为整数0。对于'22 years old'这样的字符串,它将被转换为整数22。任何不能解析为数字的都变成0。

如果你真的需要速度,我想这里的其他建议是正确的,假设强制是最快的。

您可以使用FLOAT简单地将长字符串转换为整数

$float = (float)$num;

如果你想要整数而不是浮动val,那就用val

$float = (int)$num;

前女友。

(int)   "1212.3"   = 1212 
(float) "1212.3"   = 1212.3

运行了一个基准测试,结果表明(使用所有可用的方法)获得实整数的最快方法是

$foo = (int)+"12.345";

只是用

$foo = +"12.345";

返回一个浮点数。