php - 从数据库中查找文本中的多个单词

时间:2015-11-03 13:48:03

标签: php mysql regex sql-like

我有来自Android系统的String。 我收到字符串,对应于php文件中的地址,并想检查此地址是否与我的数据库中的地址匹配。 但是,我希望它能够按照用户输入的单词的顺序工作。

起初,我使用LIKE如下:

$address=preg_replace('#\s+#','%',$_POST['address']);
    $address='%'.$address.'%';
    echo $address;
    $list_business = $bdd->prepare('SELECT * FROM business WHERE address LIKE ? OR name_business LIKE ?'); 
    $list_business->execute(array($address,$address));

这实际上允许我获得结果,即使有些单词被省略。 例如443 Street将匹配443 First Street。 但如果用户输入id为First Street 443,它将不会返回任何内容。 我在想Regex,但是它真的适应了这种问题吗?或者我应该每个单词使用一个不同的正则表达式?

1 个答案:

答案 0 :(得分:0)

您可能想看一下第三方搜索引擎,它们可以很容易地为您完成此任务。

按顺序查看SOLR,ElasticSearch和Sphinx。

你可以用Mysql的全文搜索来做到这一点,但上面的搜索引擎可以做得更好。

这是使用MySQL内置全文搜索的演示

mysql> show tables;
+----------------+
| Tables_in_test |
+----------------+
| sample         |
+----------------+
1 row in set (0.00 sec)

mysql> show create table test.sample;
+--------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table  | Create Table                                                                                                                                                       |
+--------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| sample | CREATE TABLE `sample` (
  `id` int(11) NOT NULL,
  `address` text,
  PRIMARY KEY (`id`),
  FULLTEXT KEY `ftext` (`address`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 |
+--------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

mysql> select * from test.sample;
+----+-----------------------------------------+
| id | address                                 |
+----+-----------------------------------------+
|  1 | 345 Park Avenue New York, NY 10154-0102 |
|  2 | 610 Waring Ave Bronx, New York NY 10467 |
+----+-----------------------------------------+
2 rows in set (0.00 sec)

mysql> SELECT * FROM test.sample 
    -> WHERE match(`address`)
    -> against('+new +york +ave' IN BOOLEAN MODE);
+----+-----------------------------------------+
| id | address                                 |
+----+-----------------------------------------+
|  1 | 345 Park Avenue New York, NY 10154-0102 |
|  2 | 610 Waring Ave Bronx, New York NY 10467 |
+----+-----------------------------------------+
2 rows in set (0.00 sec)

mysql> SELECT * FROM test.sample
    -> WHERE match(`address`)
    -> against('+ny +park' IN BOOLEAN MODE);
+----+-----------------------------------------+
| id | address                                 |
+----+-----------------------------------------+
|  1 | 345 Park Avenue New York, NY 10154-0102 |
+----+-----------------------------------------+
1 row in set (0.00 sec)

mysql>