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.
我有一个文本字段来接受来自UI的正则表达式。对于这些正则表达式,我有搜索功能,并希望进行搜索。我正在使用预准备语句,DB是mysql。当我在'%'上搜索时,我只想要以'%'开头的搜索正则表达式。但是,因为'%'是mysql中的通配符,所以我在搜索中获得所有正则表达式。如何逃避它。
2 个解决方案
#1
8
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 "_".
如果在模式匹配上下文之外使用“\%”或“\ _”,它们将计算字符串“\%”和“\ _”,而不是“%”和“_”。
#2
1
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), e.g. by mysql_real_escape_string()
.
\(反斜杠)和引用你当然也必须逃避(一如既往!防止SQL注入),例如通过mysql_real_escape_string()。
#1
8
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 "_".
如果在模式匹配上下文之外使用“\%”或“\ _”,它们将计算字符串“\%”和“\ _”,而不是“%”和“_”。
#2
1
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), e.g. by mysql_real_escape_string()
.
\(反斜杠)和引用你当然也必须逃避(一如既往!防止SQL注入),例如通过mysql_real_escape_string()。