preg_replace_callback 正则表达式语法不正确

preg_replace_callback regex syntax incorrect

当我搜索打开 sql 查询日志记录的 Magento 时,我发现 post 对 Magento 的核心 query 函数进行了修改,如下所示:

public function query($sql, $bind = array())
{
$this->_debugTimer();
try {
$sql = (string)$sql;
if (strpos($sql, ':') !== false || strpos($sql, '?') !== false) {
$this->_bindParams = $bind;
$sql = preg_replace_callback('#(([\'"])((2)|((.*?[^\])2)))#', array($this, 'proccessBindCallback'), $sql);
$bind = $this->_bindParams;
}
$code = 'SQL: ' . $sql . "rn";
if ($bind) {
$code .= 'BIND: ' . print_r($bind, true) . "rn";
}
$this->_debugWriteToFile("[".date('Y-m-d H:i:s')."] ".$code);
$result = parent::query($sql, $bind);
}
catch (Exception $e) {
$this->_debugStat(self::DEBUG_QUERY, $sql, $bind);
$this->_debugException($e);
}
$this->_debugStat(self::DEBUG_QUERY, $sql, $bind, $result);
return $result;
}

我不明白的是为什么这里需要 preg_replace_callback 以及当我将上面的代码放入编辑器时语法中包含 preg_replace_callback 的行中的问题是什么它显示断引号突出显示?

有什么建议吗?

你在 [^\] 附近的正则表达式中有错误,这是正确的

'#(([\'"])((2)|((.*?[^\])2)))#'

对于php字符串你还需要转义一些字符

   $re = "/#(([\'\"])((2)|((.*?[^\\])2)))#/";  
   $str = "";` 
   preg_match($re, $str, $matches);

我经常使用 https://regex101.com/ 来检查和调试正则表达式。