简体   繁体   中英

Extract 4 digit number from a text

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

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

i want use preg_match_all to extract only four digit number?

and if i want to get four digit or two digit number? (second case)

Use

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

No need to use a character class if you only have \\d to match, by the way (I omitted the square braces).

If you want to match either 4-digit or 2-digit numbers, use

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

Here I employ negative lookbehind (?<!\\d) and negative lookahead (?!\\d) to prevent matching 2-digit parts of 3-digit numbers (eg prevent matching 123 as 12 ).

To match all the 4 digit number you can use the regex \\d{4}

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

Next to match either 2 or 4 digit number you can use the regex \\d{2}|\\d{4} or a shorter regex \\d{2}(\\d{2})?

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

See it

Specify range {4} like this:

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

For two digits:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM