Search code examples
phpmysqlmetacharacters

Escaping meta characters in PHP


I was surprised to discover that the MySQL query

SELECT * WHERE name LIKE "%AFA_"; 

returns rows where name is SAFARI. To get it to match on the underscore, you have to do:

SELECT * WHERE name LIKE "%AFA\_"; 

Is there a PHP function that can do this transition or do I have to use str_replace?


Solution

  • PHP has no knowledge of MySQL LIKE wildcards, nor should it.

    It does, however, have a way to escape things in strings if you want, and that is str_replace.

    Replace instances of _ with \_, or whatever you like.

    Ultimately this question has nothing to do with MySQL.