从 PHP 中的字符串中提取浮点数
我想将字符串转换为浮点数.例如
I would like to convert a string into floating numbers. For example
152.15 x 12.34 x 11mm
进入
152.15, 12.34 and 11
并存储在一个数组中,使得 $dim[0]=152.15, $dim[1]=12.34, $dim[2]=11.
and store in an array such that $dim[0]=152.15, $dim[1]=12.34, $dim[2]=11.
我还需要处理诸如
152.15x12.34x11 mm
152.15mmx12.34mm x 11mm
谢谢.
推荐答案
$str = '152.15 x 12.34 x 11mm';
preg_match_all('!d+(?:.d+)?!', $str, $matches);
$floats = array_map('floatval', $matches[0]);
print_r($floats);
(?:...)
正则表达式构造就是所谓的 非捕获组.这意味着该块没有在 $mathces
数组的一部分中单独返回.这不是绝对必要的在这种情况下,但这是一个有用的结构.
The (?:...)
regular expression construction is what's called a non-capturing group. What that means is that chunk isn't separately returned in part of the $mathces
array. This isn't strictly necessary in this case but is a useful construction to know.
注意:调用floatval()
在元素上也不是绝对必要的,因为如果您尝试在算术运算或类似操作中使用它们,PHP 通常会正确处理类型.不过,这并没有什么坏处,尤其是只作为一个班轮.
Note: calling floatval()
on the elements isn't strictly necessary either as PHP will generally juggle the types correctly if you try and use them in an arithmetic operation or similar. It doesn't hurt though, particularly for only being a one liner.
相关文章