php - 在XPath评估之前,如何处理字符串中的双引号?

在下面的函数中,当$ keyword中的字符串包含双引号时,它会创建一个“警告:DOMXPath::evaluate():无效的表达式”:

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

最佳答案

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

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

https://stackoverflow.com/questions/15767724/

相关文章:

c++ - 在 ns 2.34 (Jiazi YI ns 2.29) 上添加 mp-olsr 时出现

arrays - 数组表达式语法错误

vba - VB-下标超出范围,错误9

compilation - Fedora 18 上的内核编译错误(在 Macbook 上的 Virt

java - 引用从对象数组进行打印的方法时找不到符号错误

java - Double不是抽象的,并且不会重写ListInterface中的抽象方法getNex

macos - 在MacOS上编译Irrlicht项目时出现“symbol(s) not found

compiler-errors - JRE 抛出的 fatal error

java - 在 int 上执行方法

java - 二进制搜索静态方法遇到问题无法引用