5

在下面的函数中,当 $keyword 中的字符串包含双引号时,它会创建一个"Warning: DOMXPath::evaluate(): Invalid expression"

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

我应该做些什么来$keyword为评估 xpath 表达式做准备?

完整的功能代码:

$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.'")])');
        }
}   
4

2 回答 2

6

PHP 有 Xpath 1.0,如果你有一个带双引号和单引号的字符串,解决方法是使用 Xpathconcat()函数。辅助函数可以决定何时使用什么。示例/用法:

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".')

辅助函数:

/**
 * 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("'" => '\', "\'", \'')) . "')";
}
于 2012-10-10T01:45:24.697 回答
4

要在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).'")])'
于 2011-01-27T18:11:07.683 回答