【问题标题】:Extract positive and negative floating point numbers from a string in php从php中的字符串中提取正负浮点数
【发布时间】:2015-06-25 19:32:02
【问题描述】:

对于 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);

唯一的问题是负值;有人可以以正确包含负数的方式为我更改表达式吗?

谢谢!

【问题讨论】:

    标签: php regex floating-point negative-number


    【解决方案1】:
    -?\d+(?:\.\d+)?
    

    这应该为你做。

    $re = "/-?\\d+(?:\\.\\d+)?/m"; 
    $str = "4.321 -3.1212"; 
    $subst = "coach"; 
    
    $result = preg_replace($re, $subst, $str);
    

    【讨论】:

    • 谢谢,但这给了我“警告:preg_match_all(): 没有找到结束分隔符 '-' 很遗憾......
    • 仍然无法正常工作...测试字符串类似于“数字是 -3.026 和 5.65 或 6525K”,我正在寻找一个包含 -3.026、5.65 和 6525 的数组... . 与上面链接中的功能相同,只是保留“-”号。
    猜你喜欢
    • 2010-10-30
    • 2020-08-04
    • 1970-01-01
    • 2021-03-24
    • 1970-01-01
    • 2022-09-23
    • 2017-06-09
    • 1970-01-01
    • 2022-01-17
    相关资源
    最近更新 更多