【问题标题】:preg_replace : capturing single quote inside single quote escaped expressionpreg_replace :在单引号转义表达式中捕获单引号
【发布时间】: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


【解决方案1】:

将带引号的字符串与最终转义的引号(或其他字符)匹配的子模式是:

'[^'\\]*+(?s:\\.[^'\\]*)*+'

(请注意,要在正则表达式模式中计算文字反斜杠,必须对其进行转义,因为反斜杠是特殊字符)

所以在一个 php 字符串中(反斜杠需要再转义一次):

$pattern = "~'[^'\\\\]*+(?s:\\\\.[^'\\\\]*)*+'~";

有了这些信息,我认为您可以自己构建模式。

详情:

'        # a literal single quote
[^'\\]*+ # zero or more characters that are not a single quote or a backslash
(?s:     # open a non-capture group with the s modifier (the dot can match newlines)
    \\.      # an escaped character
    [^'\\]*  
)*+      # repeat the group zero or more times
'

【讨论】:

    猜你喜欢
    • 2011-05-01
    • 1970-01-01
    • 2019-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多