0

Right now I have a xpath search function that looks like this:

$paragraph = $xmldoc->xpath("//p[contains(., '$wordsearch')]");

I was wondering if it is possible to let $wordsearch be a regular expression, so that my search looked something like this:

$paragraph = $xmldoc->xpath("//p[contains(., '$regularExpression')]");

Thanks for your help.

Jeff
  • 3,943
  • 8
  • 45
  • 68
  • It's [not supported](http://stackoverflow.com/questions/405060/can-i-use-a-regex-in-an-xpath-expression), because in PHP the underlying library [only implements XPath 1.0](http://stackoverflow.com/questions/2085632/will-xpath-2-0-and-or-xslt-2-0-be-implemented-in-php). – mario Jan 21 '13 at 01:47
  • erg, php is letting me down – Jeff Jan 21 '13 at 01:55
  • you can filter the return array with the regex instead. – hakre Jan 21 '13 at 02:16
  • Reference: [Using regex to filter attributes in xpath with php](http://stackoverflow.com/q/6823032/367456) (Jul 2011) – hakre Aug 17 '15 at 05:31

1 Answers1

1

You can filter the array with the regex instead:

$paragraph = array_filter(
    $xmldoc->xpath("//p"), 
    function ($p) use ($regularExpression) {
        return preg_match($regularExpression, $p);
    }
);

See array_filter.

hakre
  • 193,403
  • 52
  • 435
  • 836