用通配符搜索电话

时间:2013-04-08 15:41:34

标签: php regex preg-match

我想验证手机是否在静音中,但是使用通配符。

在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

2 个答案:

答案 0 :(得分:2)

我不会尝试匹配所有内容,而只关注数字,因为您知道自己在处理电话号码:

preg_match('/^' . str_replace('*', '\d*', $input) . '$/i' , $phone);

我写了simple test case这似乎适合你的输入。

$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

答案 1 :(得分:2)

您可以尝试\d,如下所示:

preg_match('/^' . str_replace('*', '(\d+)', $match) . '$/i' , $phone);