flash gordon Posted January 20, 2007 Share Posted January 20, 2007 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 More sharing options...
flash gordon Posted January 20, 2007 Author Share Posted January 20, 2007 Well I don't really understand why, but$pattern = '/<Template id="' . $id . '".+?<\/Template>/s';did the trick. Thanks for looking :) Link to comment https://forums.phpfreaks.com/topic/35004-help-with-non-greedy-regular-expression/#findComment-165093 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.