[英]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.