Masum Masum - 1 month ago 8
PHP Question

Using Regex find only double curly braces word from text

I have a text like this

Hello {{xyz}} how are {{abc}. I am {opq}} for your {{bpq}}.


from this text i want to find only
{{abc}
and
{opq}}
except
{{xyz}}
and
{{bpq}}
. what will be the regular expression for
php
.

I have tried this

preg_match_all("/\{{(.*?)\}}/", $mytext, $matches);

Answer

You can use this regex in PHP with PCRE verb (*SKIP)(*F) which is used to skip+fail a match in alternation.

{{[^}]*}}(*SKIP)(*F)|{{.*?}|{.*?}}

RegEx Demo

Alternatively, you can also use a lookaround based regex:

{{[^{}]*}(?!})|(?<!{){[^{}]*}}
  • (?!}) is negative lookahead to fail the match if next char is }
  • (?<!}) is negative lookbehind to fail the match if previous char is {
Comments