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 (e.g. prevent matching 123
as 12
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With