PHP - Shortest Matches Preg_match

I am trying to get "content" from this line:

$string = "start start content end";

with preg_match like this:

preg_match('/start(.*?)end/', $string, $matches);
echo $match[1];

but the problem $matches[1]returns start contentnot only contentbecause there are two startin $string(and possibly more)

How to get only contentpart with preg_match?

+4
source share
2 answers

Using a negative view:

$string = "start start content end";
preg_match('/start\h*((?:(?!start).)*)end/', $string, $matches);
echo $matches[1];
// content

(?:(?!start).)will match any character if not followed start.

+3
source

You can add +to eat everything startand then grab the desired line.

(?:start\s)+(.+?)end
0
source

Source: https://habr.com/ru/post/1613159/


All Articles