简体   繁体   English

PHP和MySql匹配字符串中的Word / Phrase

[英]PHP & MySql match a Word/Phrase in a String

i have a Table in MySql with Cities. 我在MySql中有一个表与城市。

|---------------------|------------------|
|          ID         |     City         |
|---------------------|------------------|
|          1          |     Berlin       |
|---------------------|------------------|
|          2          |     Los Angeles  |
|---------------------|------------------|
|          3          |     Shanghai     |
|---------------------|------------------|

and i have a String in Php like this: $string = "I like Berlin and Los Angeles." 我有一个像Php这样的字符串:$ string =“我喜欢柏林和洛杉矶。”

Now i want look in the MySql-Database if the String contains a City/Cities. 现在,如果字符串包含城市/城市,我想查看MySql数据库。 But i dont know what is the best solution. 但我不知道什么是最好的解决方案。 Maybe its better or/and faster to have the List with Cities as Json File? 将城市列表作为Json文件可能更好或更快?

You an use mysql query for checking it. 你使用mysql查询来检查它。

Select * from table_name where match(City) against ('I like Berlin and Los Angeles')

or you can use like 或者你可以使用喜欢

Select * from table_name where city like '%I like Berlin and Los Angeles%'

I am modified the query as you need the sort mechanism in it. 我修改了查询,因为你需要它的排序机制。

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;

It would give you sort on city present in table. 它会让你对表中的城市进行排序。

You should take all cities from database to an array then checking it. 你应该将所有城市从数据库带到一个数组,然后检查它。

$cities = ['Berlin', 'Los Angeles', 'Shanghai'];
$string = 'I like Berlin and Los Angeles.';
$result = [];
$pattern = '/('.implode('|', $cities).')/';
preg_match_all($pattern, $string, $result);

SAMPLE: http://phpio.net/s/2t70 示例: http//phpio.net/s/2t70

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM