Home > Net >  Use regex with xpath evaluate to look through every date
Use regex with xpath evaluate to look through every date

Time:10-25

I'm trying to get every item with the same ID, even though they don't have the same date.

For example, I input the ID 41 and it would then find the matching item(s) from the document which has the following items:

    <item>
      <name>Abc</name>
      <id>41:2021-10-12</id>
    </item>
    <item>
      <name>Bca</name>
      <id>41:2021-10-13</id>
    </item>
    <item>
      <name>Def</name>
      <id>42:2021-10-12</id>
    </item>
    <item>
      <name>Fed</name>
      <id>42:2021-10-13</id>
    </item>

This is what I've tried:

$trainIdDate = $trainId.':/[0-9]{4}-[0-9]{2}-[0-9]{2}/';
if ($xpath->evaluate("count(self::*[id = '$trainIdDate']) > 0", $item)) {

It works fine if I do:

$trainIdDate = $trainId.':2021-10-12';
if ($xpath->evaluate("count(self::*[id = '$trainIdDate']) > 0", $item)) {

CodePudding user response:

XPath 1.0 has no support for regular expressions.

With XPath 2.0 you can do

count(self::*[matches(id, '[0-9]{4}-[0-9]{2}-[0-9]{2}]') > 0

but the default XPath engine for PHP only supports 1.0.

CodePudding user response:

You can consider the the id a string starting with the train ID followed by a colon.

$trainID = 42;

$document = new DOMDocument();
$document->loadXML($xml);
$xpath = new DOMXpath($document);

$expression = "//item[starts-with(id, '$trainID:')]";
foreach ($xpath->evaluate($expression) as $item) {
    var_dump(
        [
            $xpath->evaluate('string(name)', $item),
            $xpath->evaluate('string(id)', $item),
        ]
    );
}
  • Related