PHP preg_match与通配符 [英] Php preg_match with wild card characters
问题描述
我在数组中有一些邮政编码,其中包括这样的通配符
I have some zip code in an array which includes some wild card characters like this
$zip_codes = array( '12556', '765547', '234*', '987*' );
$target_zip = '2347890';
因此要检查目标zip是否已存在于数组中。我是这样
So to check whether the target zip is already present in the array. I am doing like this
foreach( $zip_codes as $zip ) {
if ( preg_match( "/{$target_zip}.*$/i", $zip ) ) {
echo 'matched';
break;
}
else {
echo 'not matched';
}
}
但它根本不匹配邮政编码。有人可以告诉我这里的问题吗?
But its not matching the zip at all. Can someone tell me whats the issue here?
推荐答案
您需要打开 $ 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
您尚未表明是否要让 $ 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
.
这篇关于PHP preg_match与通配符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!