2013-04-08 220 views
-1

我想验证电话是否在通配符中,但使用通配符。带通配符的搜索电话

在foreach里面我有THW遵循代码:

$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

+1

为什么'* 7 *'不匹配?似乎应该。 – nickb 2013-04-08 15:44:22

+0

@nickb对不起,这是一个错字 – 2013-04-08 15:44:52

回答

2

您可以\d尝试,就像这样:

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

你能看到更新的问题吗? – 2013-04-08 15:55:48

+1

@GabrielSantos我更新了答案,只需使用'\ d +'而不是'\ d *' – Uby 2013-04-08 15:57:55

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 
+0

你能看到更新的问题吗? – 2013-04-08 15:55:06