Jump to content

Regex doesn't stop when it needs to.


indigo diingo

Recommended Posts

Hello

 

 

I've found a simple regex to replace the string beginning with '<span id="unique id">some text</span><span id="another unique id">some text</span><span id="another unique id">some text</span>' with 'hello'.

 

$original = preg_replace ("/<span id=\"$id\">(.*)<\/span>/",'hello',$string);

 

 

The problem now is that the regex stops at the last '</span>' tag so my hole string get replaced by 'hello' but I only want to replace the string from the beginning '<span>' tag with unique id to the FIRST end '</span>' tag, not the last.

How can I solve this?

 

 

Thanks,

Indigo

 

Link to comment
https://forums.phpfreaks.com/topic/149113-regex-doesnt-stop-when-it-needs-to/
Share on other sites

You have a laziness/greediness issue.

 

Well i would not call it lazy when i've been searching for hours to find the answer and didn't. Thanks to the other person who responded and didn't call my issue lazy.

 

Laziness and greediness are two terms used when talking about regular expressions.

 

If a search is greedy then it keeps on looking for matches as long as it can. It's wants as much as possible, it's greedy. A lazy search, however, stops as soon as it finds something that matches. It's lazy, it does the absolute minimum it has to. It's just two metaphors you use in regex. fenway wasn't talking about you being neither lazy nor greedy.

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.