How to handle double quotes in string before XPath evaluation?

后端 未结 2 1739
逝去的感伤
逝去的感伤 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:48

    PHP has Xpath 1.0, if you have a string with double and single quotes, a workaround is using the Xpath concat() function. A helper function can decide when to use what. Example/Usage:

    xpath_string('I lowe "double" quotes.');
    // xpath:    'I lowe "double" quotes.'
    
    xpath_string('It\'s my life.');
    // xpath:    "It's my life."
    
    xpath_string('Say: "Hello\'sen".');
    // xpath:    concat('Say: "Hello', "'", "'sen".')
    

    The helper function:

    /**
     * xpath string handling xpath 1.0 "quoting"
     *
     * @param string $input
     * @return string
     */
    function xpath_string($input) {
    
        if (false === strpos($input, "'")) {
            return "'$input'";
        }
    
        if (false === strpos($input, '"')) {
            return "\"$input\"";
        }
    
        return "concat('" . strtr($input, array("'" => '\', "\'", \'')) . "')";
    }
    

提交回复
热议问题