且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

PHP preg_match与通配符

更新时间:2021-10-21 15:48:07

您需要打开 $ zip $通过将 * 转换为。* (或者也许是)将c $ c>值转换为有效的正则表达式\d * );那么您可以针对 $ target_zip

You need to turn your $zip values into valid regular expressions by converting * into .* (or perhaps \d*); then you can test them against $target_zip:

$zip_codes = array( '12556', '765547', '234*', '987*' );
$target_zip = '2347890';

foreach( $zip_codes as $zip ) {
    echo $zip;
    if (preg_match('/' . str_replace('*', '.*', $zip) . '/', $target_zip)) {
        echo ' matched'. PHP_EOL;
        break;
    }
    else {
        echo ' not matched' . PHP_EOL;
    }
}

输出:

12556 not matched
765547 not matched
234* matched

在3v4l.org上进行演示

您尚未表明是否要让 $ zip_codes 中的值匹配整个 $ target_zip 值或只是它的一部分。上面的代码仅适用于部分代码(即 234 12345 匹配);如果您不希望这样做,请将正则表达式的结构更改为:

You haven't indicated whether you want the value in $zip_codes to match the entire $target_zip value or just part of it. The code above will work for just part (i.e. 234 will match 12345); if you don't want that, change the regex construction to:

if (preg_match('/^' . str_replace('*', '.*', $zip) . '$/', $target_zip)) {

锚点将确保 $ zip 与整个 $ target_zip 匹配。

The anchors will ensure that $zip matches the entirety of $target_zip.