根据MySQL手册:
MySQL uses C escape syntax in strings (for example,
\nto represent the newline character). If you want aLIKEstring to contain a literal\, you must double it. (Unless theNO_BACKSLASH_ESCAPESSQL mode is enabled, in which case no escape character is used.) For example, to search for\n, specify it as\\n. To search for\, specify it as\\\\; this is because the backslashes are stripped once by the parser and again when the pattern match is made, leaving a single backslash to be matched against.
\%匹配一个%字符。
SELECT 'David!' LIKE 'David\%'; # 0
SELECT 'David%' LIKE 'David\%'; # 1\_匹配一个_字符。
SELECT 'David!' LIKE 'David\_'; # 0
SELECT 'David_' LIKE 'David\_'; # 1若要指定其他转义字符,请使用ESCAPE子句:
SELECT 'David_' LIKE 'David|_' ESCAPE '|'; # 1更新于
2023-04-13 21:47:50
部分数据库(如SQLite、PostgreSQL、SQL Server)不支持默认转义字符,必须使用ESCAPE子句指定转义字符
更新于
2023-04-14 21:42:34
PHP 转义代码
str_replace(['\\', '_', '%'], ['\\\\', '\\_', '\\%'], $string);