Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle double quotes in string before XPath evaluation?

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

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

What should I do to prep $keyword for the evaluate xpath expression?

The 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.'")])');
        }
}   
like image 209
Scott B Avatar asked Jan 27 '11 18:01

Scott B


People also ask

Can we use double quotes in XPath?

The meaning of double quotes in XML, XPath and Java The values of XML attributes are delimited by either single or double quotes. This means that you can use double quotes as content when you use single quotes as the delimter and vice versa. You can also use the entities ' and " as a content.

How do you handle double quotes in a string?

If you need to use the double quote inside the string, you can use the backslash character. Notice how the backslash in the second line is used to escape the double quote characters. And the single quote can be used without a backslash.

How XPath handle single quotes?

XPath's string literals can't contain both types of quotes; you need to construct the string using the XPath concat function. For example, if you wanted to match the string "That's mine", he said. , you would need to do something like: text()=concat('"That', "'", 's mine", he said.


1 Answers

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("'" => '\', "\'", \'')) . "')";
}
like image 191
hakre Avatar answered Oct 27 '22 01:10

hakre