Extract 4-digit number from text

preg_match_all('/([\d]+)/', $text, $matches); foreach($matches as $match) { if(length($match) == 4){ return $match; } } 

I want to use preg_match_all to extract only a four digit number?

and if I want to get a four-digit or two-digit number? (second case)

+4
source share
3 answers

Using

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

No need to use a character class if you only have \d to match (I skipped the square brackets).

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

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

Here I use a negative lookbehind (?<!\d) and a negative lookahead (?!\d) to prevent the 2-digit parts of the three-digit numbers from matching (for example, to prevent 123 from matching as 12 ).

+11
source

To match all 4 digits, you can use the regular expression \d{4}

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

Can you use the regular expression \d{2}|\d{4} or the shorter regular expression \d{2}(\d{2})? next to the number 2 or 4 \d{2}(\d{2})?

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

Take a look

+3
source

Specify the range {4} as follows:

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

For two digits:

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

Source: https://habr.com/ru/post/1333721/


All Articles