[英]How to escape special SQL characters in regular expression in Mysql
I have a text field to accept regular expressions from the UI.我有一个文本字段来接受来自 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.我正在使用准备好的语句,数据库是 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.但是,由于 '%' 在 mysql 中是通配符,所以我在搜索中得到了所有的正则表达式。 How to escape it.如何逃脱它。
Just use a backslash before the character, as shown in the MySQL documentation section 9.1 :只需在字符前使用反斜杠,如MySQL 文档第 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):注意(来自 MySQL 文档):
If you use "\%" or "\_" outside of pattern-matching contexts, they evaluate to the strings "\%" and "\_", not to "%" and "_".如果您在模式匹配上下文之外使用“\%”或“\_”,它们的计算结果为字符串“\%”和“\_”,而不是“%”和“_”。
If you are using PHP, you may escape %, _ and characters using this code:如果您使用的是 PHP,您可以使用以下代码转义 %、_ 和字符:
$escaped = addcslashes($str, "%_");
The \ (backslash) and quotes you of course must also escape (as always, To prevent SQL injection). \(反斜杠)和引号当然也必须转义(一如既往,为了防止 SQL 注入)。 eg by mysql_real_escape_string()
.例如通过mysql_real_escape_string()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.