【问题标题】:How to regexp PHP looking for numbers in string如何正则表达式 PHP 查找字符串中的数字
【发布时间】:2017-01-22 11:40:27
【问题描述】:

我遇到了正则表达式的问题,我正在寻找解决这个问题的方法。

我需要在文本数字中查找超过 3 位的数字,但当数字在开头/最后一个 $ 字符时,我需要省略。

示例:

Lorem ipsum dolor 3232181527 amet, consectetur adipiscing $18312.90, 2432417$

在结果上我只想得到这个数字 32181527

我知道如何获取数字,但我不能省略 $ 出现的时间。

[0-9]{3,}

【问题讨论】:

    标签: php regex string split preg-match-all


    【解决方案1】:

    使用negative look-behind, negative look-ahead assertions,您可以限制不匹配特定模式之前/之后的匹配:

    $text = "Lorem ipsum dolor 32 sit 32181527 amet, consectetur adipiscing $18312.90, 2432417$.";
    preg_match_all('/(?<![0-9$])[0-9]{3,}(?![0-9$])/', $text, $matches);
    // match 3+ digits which is not preceded by digits/$.
    // also the digits should not be followed by digits/$.
    print_r($matches);
    

    输出:

    Array
    (
        [0] => Array
            (
                [0] => 32181527
            )
    
    )
    

    【讨论】:

      猜你喜欢
      • 2012-04-25
      • 2012-10-31
      • 1970-01-01
      • 2019-11-03
      • 1970-01-01
      • 2012-05-28
      • 2012-12-01
      • 1970-01-01
      • 2021-09-15
      相关资源
      最近更新 更多