在下面的函数中,当 $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,如果您有一个带有双引号和单引号的字符串,解决方法是使用 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("'" => '\', "\'", \'')) . "')";
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)