简体   繁体   中英

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

enter image description here i 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?

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

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 .

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