我想验证电话是否在数组中,但使用通配符。
在foreach中,我有以下代码:
$phone = '98765432'; // Data of stored phone
$match = '987*5432'; // Input with search term
echo preg_match('/^' . str_replace('*', '.*', $match) . '$/i' , $phone);
当我搜索以下其中一个时,preg_match
应该工作:
9*
987*5432
987*
*876*
但是,当我搜索错误的数字时,例如,preg_match
不应该工作:
8*65432
*1*
98*7777
我试过了,但找不到正确的解决办法。谢谢!编辑1
2*2*
应传递给2020
,而不传递给2002
您可以尝试使用'd
,像这样:
preg_match('/^' . str_replace('*', '('d+)', $match) . '$/i' , $phone);
我将只关注数字,而不是试图匹配所有内容,因为您知道您正在处理电话号码:
preg_match('/^' . str_replace('*', ''d*', $input) . '$/i' , $phone);
我写了一个简单的测试用例,似乎对你的输入有效。
$phone = '98765432'; // Data of stored phone
function test( $input, $phone) {
return preg_match('/^' . str_replace('*', ''d*', $input) . '$/i' , $phone);
}
echo 'Should pass:' . "'n";
foreach( array( '9*', '987*5432', '987*', '*876*') as $input) {
echo test( $input, $phone) . "'n";
}
echo 'Should fail:' . "'n";
foreach( array( '8*65432', '*1*', '98*7777') as $input) {
echo test( $input, $phone) . "'n";
}
:
Should pass:
1
1
1
1
Should fail:
0
0
0