PHP extract only 4digit numbers from string containing 4digit,5digit,6digit numbers

enter image description herei have tried many php functions like strpos(), preg_match() but none of them works. i have a string

i want to extract only the four digit number which is 1234.

<?php
 $texxt="abcd1245 784563 1234 98756 kfg7456178";
 $results=array();
 preg_match('/[0-9]{4}/', $texxt, $results);
 print_r($results);
 ?>

but the above code return 1245 instead of 1234.if i remove the abcd1245 then the out put is 7845.the actual string is very large it containg more than 200 numbers like above. i want only the exact 4 digit number. is there any way to solve this?

728x90

2 Answers PHP extract only 4digit numbers from string containing 4digit,5digit,6digit numbers

You need to place boundaries on both sides of your pattern.

\b\d{4}\b

An alternative would be to use \s instead of \b for whitespace - because boundaries will match other non-alphanumeric characters. Depends on exactly what you're looking for.

See it here

4 months ago

As you said you have more than 200 numbers then use below code:

<?php
 $texxt="abcd1245 784563 1234 3421 98756 kfg7456178";
 $results=array();
 preg_match_all('/\b\d{4}\b/', $texxt, $results);
 print_r($results);
?>

preg_match check for only one occurrence, where as preg_match_all check all occurrences. For regex explanation please refer doc.

4 months ago