Q:

Regular expression for templating captures too much

With PHP I'm trying to get my regular expression to match both template references below. The problem is, it also grabs the </ul> from the first block of text. When I remove the /s flag that it only catches the second reference. What I'm a doing wrong?  
/{{\%USERS}}(.*)?{{\%\/USERS}}/s 

Here is my string.
<ul class="users">
{{%USERS}}
<li>{%}</li>
{{%/USERS}}
</ul>

{{%USERS}} hello?!{{%/USERS}}

Why is my expression catching too much or too little?

A:

Why is my expression catching too much or too little?

Its catching too much because the quantifiers are greedy by default (see Li-aung Yip answer +1 for that)
If you remove the modifier s it matches only the second occurrence, because that modifier makes the . also match newline characters, so without it, it's not possible to match the first part, because there are newlines in between.

See the non greedy answer
{{\%USERS}}(.*?){{\%\/USERS}}

here on Regexr, a good place to test regular expressions.
Btw. I removed the ? after the capturing group, its not needed, since * matches also the empty string, so no need to make it additionally optional.

