0

I'm trying to use xpath to obtain xml node values that match a specific pattern (anything that has the pattern YYYY/MM/DD). In the example below, I would only want to find the 2nd item. I've tried using fn:matches and php:functionString with preg_match, to no avail.

<sometag>
  <link>site:www.mysite.com/2014/</link>
</sometag>
<sometag>
  <link>site:www.mysite.com/2014/01/07</link>
</sometag>

I thought I was on the right track here, but surprise surprise, it did not work.

$regex = '~(0[1-9]|1[012])[- /.](19|20)\d\d[- /.](0[1-9]|[12][0-9]|3[01])~';
$results = $xml->xpath("//link[php:functionString('preg_match', '".$regex."', .)]");

I've tried looking for just "2013" using fn:matches, this also didn't work.

$results = $xml->xpath("//link[fn:matches('2013')]");

What am I doing wrong?

1
  • Bear in mind DOMXPath only supports XPath 1.0, for your second attempt, you can use contains instead of matches Commented Nov 19, 2014 at 20:16

1 Answer 1

0

I believe you'd like to filter the DOMNodeList according to the return value of preg_match. Here's a way to do that:

    $xpath = new DOMXpath($doc);
    $xpath->registerNamespace('php', 'http://php.net/xpath');
    $xpath->registerPhpFunctions();

    $list = $xpath->query("//sometag[1 = php:function('preg_match',
                '/07/', string(link))]");

    foreach ($list as $node) {
        echo $node->nodeValue;
    }

In the snipped above, $doc refers to an instance of DOMDocument.

I am using the fact preg_match returns 1 if a match is found and 0 if not.

Note: This snippet is meant to serve as a starting point, not a final solution.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.