我有一个搜索地址数据库的应用程序。页面访问者输入他或她的地址,应用程序将告诉他们是否连接。
数据库中包含他们应该搜索的信息的相关部分是:
streetname "Stora gatan"
streetnumber "34"
streetletter "B"
address "Stora gatan 34B"
这个数据库是由我的客户提供的,正如您所看到的,它的格式很整齐。访问者搜索的绝大多数in-data是:
"Stora gatan"
"Stora gatan 34"
"Stora gatan 34b"
"Stora gatan 34 b"
这些是我目前感兴趣的仅格式。这是一个瑞典的应用程序,这就是地址在瑞典的格式/输入方式。以上的任意版本(例如,如果用户搜索"34 Storgatan B")都不会匹配任何内容,这是完全可以的。
应用程序表单应该有三个搜索字段而不是一个,这也是非常不可取的,因此in-data在一个字符串中。
现在,正如你所看到的,上面的一个搜索词会失败,尽管这是合法的输入地址的方式。就是地址的数字和字母之间有空格的那个。
所以我写了这个regexp来捕获所有传入的搜索,并希望它们是正确的:
if (preg_match("/^(.*?)s*(d*?)s*([A-Za-z]*?)$/", $address, $m)){
$streetname = uc_words($m[1]);
$streetnumber = trim($m[2]);
$streetletter = strtoupper($m[3]);
$search = trim($streetname . SPACE . $streetnumber . $streetletter);
}
不幸的是,这并没有像我希望的那样真正工作。对于上面的每个示例,生成的$m看起来像这样:
错:Array
(
[0] => Stora gatan
[1] => Stora
[2] =>
[3] => gatan
)
正确的:
Array
(
[0] => Stora gatan 34
[1] => Stora gatan
[2] => 34
[3] =>
)
正确的:
Array
(
[0] => Stora gatan 34b
[1] => Stora gatan
[2] => 34
[3] => b
)
你们有任何关于捕获所有表达式的指针,或者你会建议在regexp之前做更多的if/else捕获吗?
谢谢!
试试这个(不是最漂亮的正则表达式,但它可以工作):
$address = "Stora gatan 34 b";
preg_match("/([a-zA-Z ]+) ?([0-9]+)? ?([a-zA-Z]+)?/", $address, $m);
print_r($m);
结果:
$address = "Stora gatan 34 b";
Array ( [0] => Stora gatan 34 b [1] => Stora gatan [2] => 34 [3] => b )
$address = "Stora gatan 34b";
Array ( [0] => Stora gatan 34b [1] => Stora gatan [2] => 34 [3] => b )
$address = "Stora gatan 34";
Array ( [0] => Stora gatan 34 [1] => Stora gatan [2] => 34 )
$address = "Stora gatan";
Array ( [0] => Stora gatan [1] => Stora gatan )
$address = "Stora 34 b";
Array ( [0] => Stora 34 b [1] => Stora [2] => 34 [3] => b )
这个怎么样:
- 创建一个不包含空格的地址列:
'Storagatan34B'
- 在搜索 之前删除用户输入字符串中的所有空格
- 使用
searchcolumn LIKE <input> + '%'
当然,除了空格之外,您还可以删除希望忽略的其他字符。只要确保对搜索列和输入使用相同的替换方案即可。