Search code examples
phpmysqlsql-like

Compare string against MySQL column


Say I have the following scenario:

$string1 = 'This is my string with the city New York in';
$string2 = 'This is my string with the city Los Angeles in';

MySQL-DB:

id|city
 0|San Diego
 1|Memphis
 2|Los Angeles
 3|Budapest
 4|New York

How should I do to take the whole strings - without splitting it - and check if any of the values in city is occurring in any of the strings?

I got lots of string with more info in than stated above.


Solution

  • In MySQL you can do something like this:

    SELECT id, city
    FROM myTable
    WHERE INSTR('This is my string with the city New York in', city) > 0
    

    Something like this will find the names even if they're part of a word, so it will find Nome in "The nomenclature of Sao Paulo". Bad example, but the best I could think of: Nome matches because it's found in nomenclature. To avoid these types of matches a regular expression is needed:

    SELECT id, city
    FROM myTable
    WHERE 'This is my string with the city New York in'
          RLIKE CONCAT('(^|[^[:alpha:]])', city, '($|[^[:alpha:]])')
    

    The regex (after concatenation) would read, for example:

    (^|[^[:alpha:]])New York($|[^[:alpha:]])
    

    ... which means: Match the beginning of the string or a non-letter character, then the value "New York", then the end of the string or a non-letter character. In short, it will only find whole words.