regular expression in php: take the shortest match
Use
"/{{(.*?)}}/"
The expression ".*"
is greedy, taking as many characters as possible.
If you use ".*?"
is takes as little characters as possible, that is it stops at the first set of closing brackets.
The PCRE functions a greedy by default. That means, that the engine always tries to match as much characters as possible. The solution is simple: Just tell him to act non-greedy with the U
modifier
/{{(.+)}}/U
http://php.net/reference.pcre.pattern.modifiers
You want "ungreedy matching": preg_match("/{{(.*?)?}}/", $string)
.
Note the first question mark - a regex, by default, is "greedy": given multiple ways to match, it matches as much text as it possibly can. Adding the question mark will make it ungreedy, so if there are multiple ways to match, it will match as few characters as it possibly can.