PHP PDO与REGEXP单词边界

时间:2018-07-22 16:32:10

标签: php regex pdo

嗯,我这样尝试过:

    $sql = "SELECT * FROM 
            `quotes`
            WHERE 
            MATCH(quote) AGAINST(:against IN BOOLEAN MODE) AND
            quote REGEXP '[[:<:]]:regexp[[:>:]]'
            LIMIT 1";
$exec = $result->execute([':against' => $word, ':regexp' => $word]);

它说:

  

无效的参数编号:绑定变量的数量不匹配   令牌数量

然后这样:

$sql = "SELECT * FROM 
        `quotes`
        WHERE 
        MATCH(quote) AGAINST(:against IN BOOLEAN MODE) AND
        quote REGEXP '[[:<:]]" . PDODB::quote($word) . "[[:>:]]'
        LIMIT 1";

$exec = $result->execute([':against' => $word]);

但这会使(显然不正确的sql)

'[[:<:]]'book'[[:>:]]'

(应该是这样,但是sql注入是安全的)

'[[:<:]]book[[:>:]]'

我该怎么办? Doggo疯了。

2 个答案:

答案 0 :(得分:2)

您不引用占位符。试试:

$sql = "SELECT * FROM 
            `quotes`
            WHERE 
            MATCH(quote) AGAINST(:against IN BOOLEAN MODE) AND
            quote REGEXP concat('[[:<:]]', :regexp, '[[:>:]]')
            LIMIT 1";
$exec = $result->execute([':against' => $word, ':regexp' => $word]);

通过这种方式,:regexp将作为第二个占位符被读取。

答案 1 :(得分:1)

POSIX单词边界应该是输入字符串的一部分:

$sql = "SELECT * FROM  `quotes`
        WHERE  MATCH(quote) AGAINST(:against IN BOOLEAN MODE)
            AND quote REGEXP :regexp
        LIMIT 1";
$stmt = $pdo->prepare($sql);
$stmt->execute([':against' => $word, ':regexp' => '[[:<:]]' . $word . '[[:>:]]']);