从 php 中的字符串中提取正浮点数和负浮点数
Extract positive and negative floating point numbers from a string in php
对于 php 我必须从字符串中提取浮点数。我是正则表达式的新手,但我找到了一个在大多数情况下都适合我的解决方案:
Extract floating point numbers from a string in PHP
$str = '152.15 x 12.34 x 11mm';
preg_match_all('!\d+(?:\.\d+)?!', $str, $matches);
$floats = array_map('floatval', $matches[0]);
print_r($floats);
唯一的问题是负值;有人可以为我更改表达式,使负数也正确包含在内吗?
谢谢!
-?\d+(?:\.\d+)?
这应该可以为您完成。
$re = "/-?\d+(?:\.\d+)?/m";
$str = "4.321 -3.1212";
$subst = "coach";
$result = preg_replace($re, $subst, $str);
对于 php 我必须从字符串中提取浮点数。我是正则表达式的新手,但我找到了一个在大多数情况下都适合我的解决方案:
Extract floating point numbers from a string in PHP
$str = '152.15 x 12.34 x 11mm';
preg_match_all('!\d+(?:\.\d+)?!', $str, $matches);
$floats = array_map('floatval', $matches[0]);
print_r($floats);
唯一的问题是负值;有人可以为我更改表达式,使负数也正确包含在内吗?
谢谢!
-?\d+(?:\.\d+)?
这应该可以为您完成。
$re = "/-?\d+(?:\.\d+)?/m";
$str = "4.321 -3.1212";
$subst = "coach";
$result = preg_replace($re, $subst, $str);