使用正则表达式通过php过滤xpath中的属性 [英] Using regex to filter attributes in xpath with php

查看:94
本文介绍了使用正则表达式通过php过滤xpath中的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用匹配其id属性的正则表达式过滤html表.我究竟做错了什么?我正在尝试执行的代码:

I am trying to filter html tables with regex matching their id attribute. What am i doing wrong? Code i am trying to implement:

        $this->xpath = new DOMXPath($this->dom); 
            $this->xpath->registerNamespace("php", "http://php.net/xpath");
            $this->xpath->registerPHPFunctions();
        foreach($xpath->query("//table[php:function('preg_match', '/post\d+/', @id)]") as $key => $row)
    {

}

我得到的错误:preg_match期望第二个参数是一个字符串,给定数组.

Error that i get: preg_match expects second param to be a string, array given.

推荐答案

根据DOM(具有命名空间等),属性仍然是一个复杂元素.使用:

An attribute is still a complex element according to DOM (has a namespace etc.). Use:

//table[php:function('preg_match', '/post\d+/', string(@id))]

现在,我们需要一个布尔返回值,所以:

Now, we need a boolean return, so:

function booleanPregMatch($match,$string){
    return preg_match($match,$string)>0;
}
$xpath->registerPHPFunctions();
foreach($xpath->query("//table[@id and php:function('booleanPregMatch', '/post\d+/', string(@id))]") as $key => $row){
     echo $row->ownerDocument->saveXML($row);
}

顺便说一句:对于更复杂的问题,您当然可以偷偷检查一下这是怎么回事:

BTW: for more complex issues, you can of course sneakily check what's happening with this:

//table[php:function('var_dump',@id)]

很遗憾,我们没有可用的XPATH 2.0函数,但是如果您可以使用更不可靠的starts-with来满足此要求,那么我总是更喜欢导入PHP函数.

It's a shame we don't have XPATH 2.0 functions available, but if you can handle this requirement with a more unreliable starts-with, I'd always prefer that over importing PHP functions.

这篇关于使用正则表达式通过php过滤xpath中的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆