假设我有以下场景:
$string1 = 'This is my string with the city New York in';
$string2 = 'This is my string with the city Los Angeles in';
MySQL 数据库:
id|city
0|San Diego
1|Memphis
2|Los Angeles
3|Budapest
4|New York
我应该如何获取整个字符串 - 不拆分它 - 并检查 city 中的任何值是否出现在任何字符串中?
我得到了很多字符串,其中包含比上述更多的信息。
最佳答案
在 MySQL 中你可以这样做:
SELECT id, city
FROM myTable
WHERE INSTR('This is my string with the city New York in', city) > 0
这样的东西会找到名字,即使它们是单词的一部分,所以它会在“The nomenclature of Sao Paulo”中找到 Nome
。不好的例子,但我能想到的最好的例子:Nome
匹配,因为它在 nomenclature
中找到。为了避免这些类型的匹配,需要一个正则表达式:
SELECT id, city
FROM myTable
WHERE 'This is my string with the city New York in'
RLIKE CONCAT('(^|[^[:alpha:]])', city, '($|[^[:alpha:]])')
正则表达式(连接后)将读取,例如:
(^|[^[:alpha:]])New York($|[^[:alpha:]])
... 这意味着:匹配字符串开头 或 一个非字母字符,然后是值“New York”,然后是字符串结尾 或 非字母字符。简而言之,它只会找到完整的单词。
关于php - 将字符串与 MySQL 列进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17200803/