Jump to content

Help with non-greedy Regular Expression


flash gordon

Recommended Posts

Hi ya,

I'm trying to make a regular expression match a simple pattern. However, it is being greedy and I don't know why. Here is the php code I'm using:
[code]
// open and read the current xml doc
$filename = "myFile.xml";
$fp      = fopen($filename, "r+");
$contents = fread($fp, filesize($filename));


$id = 1;
$pattern = '/<Template id="' . $id . '".+<\/Template>?/s';
$results = preg_match_all($pattern, $contents, $matches);

print_r($matches);
[/code]

From the regEX, I would expect this:
[code]
<Template id="1">
  <node value="foobar" />
  <node value="foobar" />
  <node value="foobar" />
</Template>
[/code]

However I get this:
[code]
<Template id="1">
  <node value="foobar" />
  <node value="foobar" />
  <node value="foobar" />
</Template>
<Template id="2">
  <node value="foobar" />
  <node value="foobar" />
  <node value="foobar" />
</Template>
<Template id="3">
  <node value="foobar" />
  <node value="foobar" />
  <node value="foobar" />
</Template>
</Templates>
[/code]

Can anyone spot my error? Apparently the regEX going to the complete end of the file.
Link to comment
https://forums.phpfreaks.com/topic/35004-help-with-non-greedy-regular-expression/
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.