Using regex to filter attributes in xpath with php

前端 未结 2 1294
不思量自难忘°
不思量自难忘° 2020-11-29 11:56

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 =          


        
2条回答
  •  半阙折子戏
    2020-11-29 12:16

    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)]
    

    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.

提交回复
热议问题