Search code examples
phpregexpreg-match

PHP - Preg_match shortest matches


I'm trying to get "content" from this string:

$string = "start start content end";

with preg_match like this:

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

but, problem is $matches[1] returns start content not only content because there are two start in $string (and maybe more)

How to get only content part with preg_match?


Solution

  • Using a negative lookahead:

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

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