Using regex to filter attributes in xpath with php

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.

Leave a Comment

tech