我想将字符串转换为浮点数.例如
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 中的字符串中提取浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
以编程方式将可下载文件添加到 Woocommerce 产品Add programmatically a downloadable file to Woocommerce products(以编程方式将可下载文件添加到 Woocommerce 产品)
获取今天 Woocommerce 中每种产品的总订单数Get today#39;s total orders count for each product in Woocommerce(获取今天 Woocommerce 中每种产品的总订单数)
在 WooCommerce 和电话字段验证问题中添加自定义注Add Custom registration fields in WooCommerce and phone field validation issue(在 WooCommerce 和电话字段验证问题中添加自定义注册字段
在 Woocommerce 简单产品中添加一个将更改价格的选Add a select field that will change price in Woocommerce simple products(在 Woocommerce 简单产品中添加一个将更改价格的选择字段)
在 WooCommerce 3 中将自定义列添加到管理产品列表Add custom columns to admin products list in WooCommerce 3(在 WooCommerce 3 中将自定义列添加到管理产品列表)
自定义结帐“下订单"按钮输出htmlCustomizing checkout quot;Place Orderquot; button output html(自定义结帐“下订单按钮输出html)