从 PHP 中的分隔字符串中提取浮点数
我想将一串分隔的维度值转换为浮点数。
例如,
152.15 x 12.34 x 11mm
存储在
152.15, 12.34 and 11
数组中:
$dim[0] = 152.15;
$dim[1] = 12.34;
$dim[2] = 11;
我还需要处理分隔文本不同并且数字后面可能跟有单位表达式的情况,例如:
152.15x12.34x11 mm
152.15mmx12.34mm x 11mm
I would like to convert a string of delimited dimension values into floating numbers.
For example
152.15 x 12.34 x 11mm
into
152.15, 12.34 and 11
and store in an array such that:
$dim[0] = 152.15;
$dim[1] = 12.34;
$dim[2] = 11;
I would also need to handle scenarios where the delimiting text is different and the numbers may be followed by a unit expression like:
152.15x12.34x11 mm
152.15mmx12.34mm x 11mm
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
(?:...)
正则表达式构造就是所谓的 非捕获组。 这意味着块不会在$mathces
数组的一部分中单独返回。 在本例中这并不是绝对必要的,但了解它是一个有用的结构。注意:调用
floatval()
elements 也不是绝对必要的,因为如果您尝试在算术运算或类似操作中使用它们,PHP 通常会正确地处理类型。 不过,这并没有什么坏处,特别是对于只有单层的情况。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.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.给出
gives
测试了一下,它适用于上面的所有字符串。
Tested it and it works on all strings above.
使用
sscanf()
提供与preg_
函数调用相同级别的所需灵活性,但sscanf()
更好,因为它允许您显式地将目标值从其format
参数转换为浮点数。%f
表示浮点数子字符串,并且%*[mx ]
匹配并默默地忽略不需要的分隔符。现在无需在
array_map()
中调用floatval()
来转换浮点值。代码:(演示)
输出:
Using
sscanf()
affords the same level of required flexibility as apreg_
function call, butsscanf()
is better because it allows you to explicitly cast the targeted values as floats from itsformat
parameter.%f
means a float number substring and%*[mx ]
matches and silently ignores the unwanted separators.Now there is no need to call
floatval()
withinarray_map()
to cast the float values.Code: (Demo)
Output:
此示例也支持像 .11 这样的数字,因为它们是有效数字。
$matches[0]
将包含 152.15、12.34 和 0.11,前提是您键入将结果强制转换为 float 。 如果不这样做,0.11 将显示为 .11。 我会使用array_map
进行强制转换。您可以将这些值用于任何数学运算,而无需进行类型转换。 直接打印时只需要铸造即可。
This example supports numbers like .11 as well, since they are valid numbers.
$matches[0]
will contain 152.15, 12.34 and 0.11, given that you type cast the result to float. If you don't 0.11 will appear as .11. I would type cast usingarray_map
.You can use the values for anything math without type casting them though. casting is just needed when printing them directly.