沃梦达 / 编程问答 / php问题 / 正文

从 PHP 中的字符串中提取浮点数

Extract floating point numbers from a string in PHP(从 PHP 中的字符串中提取浮点数)

本文介绍了从 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 中的字符串中提取浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:从 PHP 中的字符串中提取浮点数

基础教程推荐