[英]php - Find multiple words in text from database
我有一個來自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街將匹配443第一街。 但是,如果用戶鍵入id為First Street 443,它將不會返回任何內容。我在考慮正則表達式,但是它真的適合這種問題嗎? 還是每個字應該使用一個不同的正則表達式?
您可能想看一下第三方搜索引擎,它可以很輕松地為您完成此任務。
按順序查看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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.