gpt4 book ai didi

php - 从 PHP 中的分隔字符串中提取 float

转载 作者:可可西里 更新时间:2023-11-01 12:25:35 25 4
gpt4 key购买 nike

我想将一串带分隔符的维度值转换为 float 。

例如

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

最佳答案

$str = '152.15 x 12.34 x 11mm';
preg_match_all('!\d+(?:\.\d+)?!', $str, $matches);
$floats = array_map('floatval', $matches[0]);
print_r($floats);

(?:...) 正则表达式构造称为 non-capturing group .这意味着 block 不会在 $mathces 数组的一部分中单独返回。这不是绝对必要的在这种情况下,但这是一个有用的结构。

注意:调用floatval()如果您尝试在算术运算或类似操作中使用它们,PHP 通常会正确处理元素类型。不过,这并没有什么坏处,特别是对于仅作为一个类轮的人来说。

关于php - 从 PHP 中的分隔字符串中提取 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/944400/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com