从PHP中的字符串中提取浮点数 [英] Extract floating point numbers from a string in 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.
这篇关于从PHP中的字符串中提取浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!