-1

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?

m02ph3u5
  • 3,022
  • 7
  • 38
  • 51
Scott C Wilson
  • 19,102
  • 10
  • 61
  • 83
  • 1
    I don't understand, you are demonstrating how to select a value based on a pattern using mysql and asking how to replace a string in php... How exactly the both are related to one another? – Alon Eitan Nov 24 '19 at 19:10
  • 1
    Possible duplicate of https://stackoverflow.com/questions/3683746/escaping-mysql-wild-cards – kmoser Nov 24 '19 at 19:11
  • 1
    If you want ``LIKE`` to match a literal underscore, you must escape it with ``\``, e.g. ``SELECT * WHERE name LIKE "%AFA\_";``. You can also specify a custom escape character: https://dev.mysql.com/doc/refman/8.0/en/string-comparison-functions.html#operator_like – kmoser Nov 24 '19 at 19:13

1 Answers1

2

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.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055