Search code examples
phparraysregexmatchcontain

PHP regex - check if string contains a given value with certain count of random digits in the end


I have few strings in an array:

$array = array('BE001 FIRST', 'BE01 SECOND', 'SV001 THIRD');

foreach ($array as $item) {
    // preg_match('', $item);
}

I would like to get an array element if it contains "BE" + 3 of any digits right after. In this case 1st array element.

I am not familiar to regex, but I saw examples how to match a given value, but not a given value with the certain count of random digits at the end. Please help me!


Solution

  • Use preg_grep:

    $array = array('BE001 FIRST', 'BE01 SECOND', 'SV001 THIRD');
    $res = preg_grep('/^BE\d{3}\b/', $array);
    print_r($res);
    

    Output:

    Array
    (
        [0] => BE001 FIRST
    )