【发布时间】:2015-10-09 19:38:25
【问题描述】:
在 wordpress 主题中,我使用“posts_where”过滤器将搜索添加到“摘录”字段。它在搜索字符串中有单引号时除外,这会导致 SQL 语法错误。
这似乎是 post_where 过滤器的 preg_replace 函数中的错误。
例如,对于字符串 "o'kine" ,posts_where 过滤器中接收到的 $where 字符串是:
"AND (((cn_posts.post_title LIKE '%o\'kine%') OR (cn_posts.post_content LIKE '%o\'kine%')))"
那么这是我的 preg_replace 添加 post_excerpt 字段:
$where = preg_replace(
"/post_title\s+LIKE\s*(\'[^\']+\')/",
"post_title LIKE $1) OR (post_excerpt LIKE $1", $where );
以及$where后面的值:
"AND (((cn_posts.post_title LIKE '%o\') OR (post_excerpt LIKE '%o\'kine%') OR (cn_posts.post_content LIKE '%o\'kine%')))"
查看导致 SQL 语法错误的 '%o\' 部分。
预期的结果是:
"AND (((cn_posts.post_title LIKE '%o\'kine%') OR (post_excerpt LIKE '%o\'kine%') OR (cn_posts.post_content LIKE '%o\'kine%')))"
错误显然在我的正则表达式中,更准确地说是在我的捕获括号中。我不知道如何处理我的搜索字符串中出现零个或多个单引号的可能性?
编辑:使用 Casimir et Hippolyte 的答案,这是搜索字符串中带有单引号的工作过滤器:
function cn_search_where( $where ) {
$where = preg_replace(
"/post_title\s+LIKE\s*('[^'\\\\]*+(?s:\\\\.[^'\\\\]*)*+')/",
"post_title LIKE $1) OR (post_excerpt LIKE $1", $where );
return $where;
}
【问题讨论】:
-
请清晰简洁地分享输入和预期输出以及当前输出(如果有)
标签: mysql sql regex wordpress preg-replace