phpregexregex-greedyquantifiersnon-greedy

Greedy quantifier is matching two consecutive segments instead of making two separate matches


Here is the code I'm using;

$string = "[if-protectDelete-{0}-][data]name[/data] can be deleted[/elseif][elseif-{1}-][data]name[/data] can't be deleted[/elseif][elseif-{2}-]No data[/elseif][/endif]";

if (preg_match_all("#\[elseif-\{(.+)\}-\](.+?)\[/elseif\]#", $string, $matches)) {
    dumper($matches[0]);
}

$matches[0] output is;

array(1) {
  [0]=> string(75) "[elseif-{1}-]PHP REGEX can't be deleted[/elseif][elseif-{2}-]No data[/elseif]"
}

I can get the part right for if, but elseif... It is totally different scenario I guess. Shouldn't it output like this?

array {
  [0] => "[elseif-{1}-]PHP REGEX can't be deleted[/elseif]",
  [1] => "[elseif-{2}-]No data[/elseif]"
}

Solution

  • Just add ?

    your : \[elseif-\{(.+)\}-\](.+?)\[/elseif\]
    right: \[elseif-\{(.+?)\}-\](.+?)\[/elseif\]