[英]PHP & MySql match a Word/Phrase in a String
我在MySql中有一個表與城市。
|---------------------|------------------|
| ID | City |
|---------------------|------------------|
| 1 | Berlin |
|---------------------|------------------|
| 2 | Los Angeles |
|---------------------|------------------|
| 3 | Shanghai |
|---------------------|------------------|
我有一個像Php這樣的字符串:$ string =“我喜歡柏林和洛杉磯。”
現在,如果字符串包含城市/城市,我想查看MySql數據庫。 但我不知道什么是最好的解決方案。 將城市列表作為Json文件可能更好或更快?
你使用mysql查詢來檢查它。
Select * from table_name where match(City) against ('I like Berlin and Los Angeles')
或者你可以使用喜歡
Select * from table_name where city like '%I like Berlin and Los Angeles%'
我修改了查詢,因為你需要它的排序機制。
Select *,(match(City) against ('I like Los Angeles and Berlin')) as relevance from city
where match(City) against ('I like Los Angeles and Berlin') ORDER BY relevance ASC;
它會讓你對表中的城市進行排序。
你應該將所有城市從數據庫帶到一個數組,然后檢查它。
$cities = ['Berlin', 'Los Angeles', 'Shanghai'];
$string = 'I like Berlin and Los Angeles.';
$result = [];
$pattern = '/('.implode('|', $cities).')/';
preg_match_all($pattern, $string, $result);
示例: http : //phpio.net/s/2t70
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.