[英]How to escape special SQL characters in regular expression in Mysql
我有一个文本字段来接受来自 UI 的正则表达式。 对于这些正则表达式,我有搜索能力,想做一个搜索。 我正在使用准备好的语句,数据库是 mysql。 当我在“%”上进行搜索时,我只想搜索以“%”开头的正则表达式。 但是,由于 '%' 在 mysql 中是通配符,所以我在搜索中得到了所有的正则表达式。 如何逃脱它。
只需在字符前使用反斜杠,如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.
注意(来自 MySQL 文档):
如果您在模式匹配上下文之外使用“\%”或“\_”,它们的计算结果为字符串“\%”和“\_”,而不是“%”和“_”。
如果您使用的是 PHP,您可以使用以下代码转义 %、_ 和字符:
$escaped = addcslashes($str, "%_");
\(反斜杠)和引号当然也必须转义(一如既往,为了防止 SQL 注入)。 例如通过mysql_real_escape_string()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.