You want to use non-greedy quantifiers, removing the optional part from the third capturing group and placing that group inside of the non-capturing group.
/{\?if ([^{}]+)}(.+?)(?:{\?else}(.+?))?{\?endif}/g You want to use non-greedy quantifiers, removing the optional part from the third capturing group and placing that group inside of the non-capturing group.
/{\?if ([^{}]+)}(.+?)(?:{\?else}(.+?))?{\?endif}/g