簡體   English   中英

從文本中提取4位數字

[英]Extract 4 digit number from a text

    preg_match_all('/([\d]+)/', $text, $matches);

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

我想用preg_match_all只提取四位數?

如果我想得到四位數或兩位數? (第二種情況)

采用

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;

在這里,我使用負向lookbehind (?<!\\d)和負向前導(?!\\d)來防止匹配3位數字的2位數部分(例如,防止匹配12312 )。

要匹配所有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);

看見

像這樣指定范圍{4}

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

兩位數:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM