我尝试在mysql中使用正则表达式,除了在单词中使用引号外,它运行良好。
例如:
SELECT * FROM table WHERE REGEXP "^pagina's[^[:space:]]*$"
我尝试了以下所有方法:
SELECT * FROM table WHERE REGEXP "^'.preg_quote("pagina's").'[^[:space:]]*$"
和
SELECT * FROM table WHERE REGEXP "^'.addslashes("pagina's").'[^[:space:]]*$"
和
SELECT * FROM table WHERE REGEXP "^'.mysql_escape_real_string("pagina's").'[^[:space:]]*$"
没有运气..
它不会给我任何结果,因为单词"pagina's"中的单引号 (')。
如何转义所有引号,以便 mysql 看到引号文字并匹配数据库中的字段?
**编辑**
这是我的PHP代码:
$word = "pagina's";
$ary[] = "LOWER(idx.sidx_word) REGEXP '^".preg_quote($word)."[^[:space:]]*$'";
您需要指定表和列名...而且您没有正确转义报价。 尝试这样的事情:
SELECT *
FROM table
WHERE column REGEXP '^pagina''s[^[:space:]]*$';
您必须为正则表达式指定列名,并用斜杠来区分引号:
SELECT *
FROM table
WHERE column REGEXP '^pagina's[^[:space:]]*$';
您可以在将单引号/双引号括起来以匹配双引号/单引号之间交替使用。要匹配任何字符,请将要匹配的字符括在"[]"中。当特殊字符(例如"[","]","\")时,在"[]"栏内加上反斜杠前缀。
要解决在 REGEXP 匹配中同时使用单引号和双引号或匹配任何字符的问题,如果需要,请使用 CONCAT() 和 CHAR() 构造正则表达式。请参阅下面我的示例:
/* create test string (377 is octal): abc'377"de\f[x] */
SET @tststr := CONCAT("abc'",char(255),'"de\f[x]' );
SELECT @tststr; /*show the test string */
SELECT @tststr REGEXP "'" ; /* match single quote */
SELECT @tststr REGEXP '"' ; /* match double quote */
SELECT @tststr REGEXP char(255) ; /* match xfe char */
SELECT @tststr REGEXP '\' ; /* FAIL: match backslash: this one fails */
SELECT @tststr REGEXP '[\]' ; /* OK: match backslash */
SELECT @tststr REGEXP 'f[[]x[]]$' ; /* OK: match ending sequence */
SELECT @tststr REGEXP 'f[[]x[]]$' ; /* OK: oddly, this works too (unbalanced brackets) */
/* Match entire sequence. Some characters may not need "[]" enclosing.
* CONCAT() may be needed to construct the complex regular expressions.
*/
SELECT @tststr REGEXP CONCAT("^abc'",char(255),'"de[\]f[[]x[]]$' ) ;
SELECT @tststr REGEXP CONCAT("^abc'[",char(255),']"de[\]f[[]x[]]$' ) ; /* OK: This works too */