Search code examples
phpregexpreg-match-all

preg_match_all query to only display the outer group having issues


I can't work out how to only show the outer group level of a preg query, I'll give you the example.

preg_match_all('/start(.*?)end/', $input, $matches);

This input start1 start2 2end 1end produces this output start1 start2 2end.

As you can see it doesn't group properly - what am I doing wrong?


Solution

  • Perhaps you need to make the dot in .* greedy, rather than lazy. As an example:

    $input = "blah blah start1 hello start2 blah 2end 1end";
    preg_match_all('/start(.*)end/', $input, $matches);
    print_r($matches[0][0]);
    

    This prints:

    start1 hello start2 blah 2end 1end