PHP 正则表达式 - 检查字符串是否包含给定值,最后有一定数量的随机数字

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

我的数组中只有几个字符串:

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

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

我想得到一个数组元素,如果它紧接着包含 "BE" + 3 个任意数字。在这种情况下,第一个数组元素。

我对 regex 不熟悉,但我看到了如何匹配给定值的示例,但不是给定值与最后一定数量的随机数字匹配。请帮助我!

使用preg_grep:

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

输出:

Array
(
    [0] => BE001 FIRST
)

这是我的版本:

<?php
$input = ['BE001 FIRST', 'BE01 SECOND', 'SV001 THIRD', 'BE1234 FOURTH'];
$output = [];
array_walk($input, function(&$entry) use (&$output) {
    if (preg_match('/BE\d{3}([^\d]|$)/', $entry)) {
        $output[] = $entry;
    }
});
print_r($output);

输出显然是:

Array
(
    [0] => BE001 FIRST
)