How to handle double quotes in string before XPath evaluation?

后端 未结 2 1735
逝去的感伤
逝去的感伤 2020-11-27 23:03

In the function below, when string in $keyword contains double quotes, it does create a \"Warning: DOMXPath::evaluate(): Invalid expression\":

$keyw         


        
2条回答
  •  自闭症患者
    2020-11-27 23:27

    To escape the string delimiters in XPath 2.0 string literals you need to replace each single delimiter by two, so " needs to be replaced by "":

    [74]      StringLiteral      ::=      ('"' (EscapeQuot | [^"])* '"') | ("'" (EscapeApos | [^'])* "'") /* ws: explicit */
    [75]      EscapeQuot     ::=      '""'
    [76]      EscapeApos     ::=      "''"
    

    I’m not sure if there already is a function to do that but you can use this function:

    function xpath_quote($str, $quotation='"') {
        if ($quotation != '"' && $quotation != "'") return false;
        return str_replace($quotation, $quotation.$quotation, $str);
    }
    

    And the usage:

    'boolean(/html/body//'.$heading.'[contains(.,"'.xpath_quote($keyword).'")])'
    

提交回复
热议问题