Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 757
Leonardo Avatar asked Dec 06 '22 00:12

Leonardo


1 Answers

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 (e.g. prevent matching 123 as 12).

like image 187
BoltClock Avatar answered Dec 10 '22 11:12

BoltClock