【问题标题】:Extract 4 digit number from a text从文本中提取 4 位数字
【发布时间】:2010-12-29 18:34:06
【问题描述】:
    preg_match_all('/([\d]+)/', $text, $matches);

    foreach($matches as $match)
    {
        if(length($match) == 4){
            return $match;
        }
    }

我想使用 preg_match_all 只提取四位数字?

如果我想获得四位数或两位数? (第二种情况)

【问题讨论】:

    标签: php regex preg-match


    【解决方案1】:

    使用

    preg_match_all('/(\d{4})/', $text, $matches);
    return $matches;
    

    顺便说一下,如果你只有 \d 来匹配,则不需要使用字符类(我省略了方括号)。

    如果要匹配 4 位或 2 位数字,请使用

    preg_match_all('/(?<!\d)(\d{4}|\d{2})(?!\d)/', $text, $matches);
    return $matches;
    

    在这里,我使用负后瞻 (?&lt;!\d) 和负前瞻 (?!\d) 来防止匹配 3 位数字的 2 位部分(例如,防止将 123 匹配为 12)。

    【讨论】:

      【解决方案2】:

      要匹配所有4 数字号码,您可以使用正则表达式\d{4}

      preg_match_all('/\b(\d{4})\b/', $text, $matches);
      

      接下来要匹配24 数字号码,您可以使用正则表达式\d{2}|\d{4} 或更短的正则表达式\d{2}(\d{2})?

      preg_match_all('/\b(\d{2}(\d{2})?)\b/', $text, $matches);
      

      See it

      【讨论】:

        【解决方案3】:

        像这样指定范围{4}

        preg_match_all('/(\d{4})/', $text, $matches);
        

        两位数:

        preg_match_all('/(\d{2})/', $text, $matches);
        

        【讨论】:

        • @BoltClock:在看到你的评论之前更新了 :)
        猜你喜欢
        • 2013-05-14
        • 1970-01-01
        • 1970-01-01
        • 2018-06-01
        • 1970-01-01
        • 2020-12-28
        • 2016-10-27
        • 2015-03-19
        相关资源
        最近更新 更多