How to handle double quotes in a string before evaluating XPath?

In the function below, when the string in the $ keyword contains double quotes, it creates a "Warning: DOMXPath :: evaluation (): Invalid expression":

$keyword = 'This is "causing" an error';
$xPath->evaluate('boolean(//img[contains(@alt, "'.$keyword.'")])');

What should I do with prep $keywordto express an xpath expression?

Full function code:

$keyword = trim(strtolower(rseo_getKeyword($post)));

function sx_function($heading, $post){
    $content = $post->post_content;
    if($content=="" || !class_exists('DOMDocument')) return false;
    $keyword = trim(strtolower(rseo_getKeyword($post)));
    @$dom = new DOMDocument;
    @$dom->loadHTML(strtolower($post->post_content));
    $xPath = new DOMXPath(@$dom);
    switch ($heading)
        {
        case "img-alt": return $xPath->evaluate('boolean(//img[contains(@alt, "'.$keyword.'")])');
        default: return $xPath->evaluate('boolean(/html/body//'.$heading.'[contains(.,"'.$keyword.'")])');
        }
}   
+3
source share
2 answers

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

xpath_string('I lowe "double" quotes.');
// xpath:    'I lowe "double" quotes.'

xpath_string('It\ my life.');
// xpath:    "It my life."

xpath_string('Say: "Hello\'sen".');
// xpath:    concat('Say: "Hello', "'", "'sen".')

Auxiliary 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("'" => '\', "\'", \'')) . "')";
}
+6
source

XPath 2.0, , " "":

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

, , :

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

:

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

Source: https://habr.com/ru/post/1788277/


All Articles