How to escape special SQL characters in regular expression in Mysql

匿名 (未验证) 提交于 2019-12-03 00:50:01

问题:

I have a text field to accept regular expressions from the UI. For these regular expressions, I have a search capability and want to do a search. I am using prepared statements and the DB is mysql. When I do a search on '%', I only want search regex starting with '%'. But, since '%' is wildcard in mysql, I get all the regex in the search. How to escape it.

回答1:

Just use a backslash before the character, as shown in the MySQL documentation section 9.1:

\0  An ASCII NUL (0x00) character.   \'  A single quote ("'") character.   \"  A double quote (""") character.   \b  A backspace character.   \n  A newline (linefeed) character.   \r  A carriage return character.   \t  A tab character.   \Z  ASCII 26 (Control+Z). See note following the table.   \\  A backslash ("\") character.   \%  A "%" character. See note following the table.   \_  A "_" character. See note following the table.  

Note (from the MySQL documentation):

If you use "\%" or "\_" outside of pattern-matching contexts, they evaluate to the strings "\%" and "\_", not to "%" and "_".



回答2:

If you are using PHP, you may escape %, _ and characters using this code:

$escaped = addcslashes($str, "%_");

The \ (backslash) and quotes you of course must also escape (as always! To prevent SQL injection), e.g. by mysql_real_escape_string().



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!