简体   繁体   中英

Extract 5 or 6 Digit Numbers from the string

I am trying to extract 5 or 6 digit numbers only from the string. below are code which i have tried but it is not as expected.

$str1 = "21-114512"; //it should return 114512      
$str2 = "test12345abcd"; //it should return 12345   
$str3 = "12test123456testing"; //it should return 123456    

function extract_numbers($string)
{
   preg_match_all('/\b[^\d]*\d{6}[^\d]*\b/', $string, $match);

   return $match[0];
}

print_r(extract_numbers($str1));

Lookarounds and a ranged quantifier should do the trick.

The pattern logic says find a sequence of 5 or 6 digits, then look before and after the matched digits to ensure that there is not a digit on either side.

Code ( Demo )

$strings = [
    "21-114512",
    "test12345abcd",
    "12test123456testing",
    "123456",
    "1234",
    "12345a67890"
];
function extract_numbers($string)
{
   return preg_match_all('/(?<!\d)\d{5,6}(?!\d)/', $string, $match) ? $match[0] : [];
}
foreach ($strings as $string) {
    var_export(extract_numbers($string));
    echo "\n---\n";
}

Output:

array (
  0 => '114512',
)
---
array (
  0 => '12345',
)
---
array (
  0 => '123456',
)
---
array (
  0 => '123456',
)
---
array (
)
---
array (
  0 => '12345',
  1 => '67890',
)
---

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