PHP XPath结尾

时间:2011-03-25 16:32:27

标签: php xpath

  

可能重复:
  How to use XPath function in a XPathExpression instance programatically?

我正在尝试查找嵌套表的所有行,其中包含一个id为'_imgProductImage'的图像。

我正在使用以下查询:

"//tr[/td/a/img[ends-with(@id,'_imgProductImage')]"

我收到错误: xmlXPathCompOpEval:函数结束 - 未找到

我的谷歌搜索我相信说这应该是一个有效的查询/功能。如果它不是“结束”,我正在寻找的实际功能是什么?

4 个答案:

答案 0 :(得分:12)

来自How to use XPath function in a XPathExpression instance programatically?

  

可以轻松构造一个XPath 1.0表达式,其评估结果与函数ends-with()产生相同的结果:

     

$str2 = substring($str1, string-length($str1)- string-length($str2) +1)

     

生成相同的布尔结果(true()false()):

     

ends-with($str1, $str2)

因此,对于您的示例,以下xpath应该起作用:

//tr[/td/a/img['_imgProductImage' = substring(@id, string-length(@id) - 15)]

你可能想要添加一条注释,这是ends-with()的xpath 1.0重构。

答案 1 :(得分:9)

似乎ends-with()是XPath 2.0 函数。

DOMXPath仅支持XPath 1.0


在评论后进行修改:在您的情况下,我认为您必须:

  • 使用更简单的XPath查询查找所有图像,这些图像将返回比您想要的图像更多的图像 - 但包括您想要保留的图像。
  • 如果id属性(请参阅getAttribute方法)符合您的要求,则为每个人循环使用PHP进行测试。

要测试属性是否正常,您可以在遍历图像的循环中使用类似的内容:

$id = $currentNode->getAttribute('id');
if (preg_match('/_imgProductImage$/', $id)) {
    // the current node is OK ;-)
}

请注意,在我的正则表达式模式中,我使用$来表示字符串结尾

答案 2 :(得分:5)

XPath 1.0中没有ends-with函数,但您可以伪造它:

"//tr[/td/a/img[substring(@id, string-length(@id) - 15) = '_imgProductImage']]"

答案 3 :(得分:4)

如果您使用的是PHP 5.3.0或更高版本,则可以使用registerPHPFunctions来调用所需的任何PHP函数,尽管语法有点奇怪。例如,

$xpath = new DOMXPath($document);
$xpath->registerNamespace("php", "http://php.net/xpath");
$xpath->registerPHPFunctions("ends_with");
$nodes = $x->query("//tr[/td/a/img[php:function('ends-with',@id,'_imgProductImage')]"

function ends_with($node, $value){
    return substr($node[0]->nodeValue,-strlen($value))==$value;
}