therealwesfoster Posted May 17, 2008 Share Posted May 17, 2008 When I run a preg_match, and there are multiple </b> (where i want the regex to stop), how can I make it stop at the NEXT occurrence? Sometimes it skips all the way to the last occurrence, or somewhere in between. IE: Here's my sample code: <h2> <i> <div> <b> <i id="2">My text!</i> </b> </div> </i> </h2> And my regex: (this is a quick throw-together.. non tested. just to help me ask my question) <?php $string = file_get_contents("THE_ABOVE_CODE"); $body = preg_match('/\<i id="2">(.*)\<\/i>/ism',$string,$match); echo "<pre>".print_r($match)."</pre>"; ?> Now in the code, instead of selecting the </i> right after the text "My Text!", it selects the last </i> in the script... why? Thanks Quote Link to comment Share on other sites More sharing options...
Orio Posted May 17, 2008 Share Posted May 17, 2008 What you're looking for is the laziness operator "?". Here's how your regular expression should look like: (Just added the laziness operator) $body = preg_match('/\<i id="2">(.*?)\<\/i>/ism',$string,$match); Orio. Quote Link to comment Share on other sites More sharing options...
therealwesfoster Posted May 17, 2008 Author Share Posted May 17, 2008 Sweet, I'll give it a try. Does the ? just mean "be lazy and grab the first one you see"? Wes Quote Link to comment Share on other sites More sharing options...
Orio Posted May 17, 2008 Share Posted May 17, 2008 It works so the part in brackets will match the shortest part possible, instead of matching the longest part found (that's the default). Orio. Quote Link to comment Share on other sites More sharing options...
therealwesfoster Posted May 17, 2008 Author Share Posted May 17, 2008 Worked like a charm. Thanks Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.