To discriminate between triple and double braces you need to use lookarounds.
To only match double opening braces, use
(?<!{){{2}(?!{)
Here, (?<!{)
is a negative lookbehind that makes sure there is no {
before the first {
and (?!{)
is a negative lookahead that makes sure there is no {
after the second {
. See regex demo here.
To only match triple opening braces use
(?<!{){{3}(?!{)
See another regex demo
Just use }
in all the above expressions to match closing braces.
Note that there is no need to escape {
and }
in PHP regex, the engine is smart enough to know they are not part of the limiting quantifier.
To get all substrings between {{{
and }}}
, you can use
'~(?<!{){{{(?!{)\s*(.*?)\s*(?<!})}}}(?!})~s'
See the 3rd regex demo. PHP code:
$re = '~(?<!{){{{(?!{)\s*(.*?)\s*(?<!})}}}(?!})~s';
$str = "{{{ hello{{there}} }}} {{{good {{morning}} }}}";
preg_match_all($re, $str, $matches);
print_r($matches[1]);
Output:
[0] => hello{{there}}
[1] => good {{morning}}
Also note that in case you have no quadruple {
s and }
s, you can omit the lookarounds and use '~{{{\s*(.*?)\s*}}}~s'
.