Search code examples
phpregexpreg-match-allextractdigits

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));

Solution

  • 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',
    )
    ---