I have a regex that matches a string and uses the non-greedy syntax so it stops at the first ending match. I need it to stop at the second ending match. How would I do that?
$text = "start text1 end text2 end text3 end";
$regex = "~start.+?end~";
preg_match($regex, $text, $match);
print_r($match);
Result:
start text1 end
Need Result
start text1 end text2 end
The following should work, you just have to repeat the expression sequence you want again. There are a few ways to do it. The simplest way is:
$text = "start text1 end text2 end text3 end";
$regex = "~start.+?end.+?end~";
preg_match($regex, $text, $match);
print_r($match);
You may also want to use an exact quantifier to describe the pattern:
$text = "start text1 end text2 end text3 end";
$regex = "~start(.+?end){2}~";
preg_match($regex, $text, $match);
print_r($match);
The "{2}" tells it to match everything in the parentheses before it exactly twice.