Search code examples
phpregexpreg-grep

Get strings which are inside double braces


I have a string where some part of the string is inside braces, and I would like to get them in an array.

The string is for example: Lorem {{ipsum}} dolor sit amet, {{consectetur}} adipiscing elit.

And I would like to get: array("ipsum", "consectetur")

I tried this:

$regExp = "/\{\{([^)]+)\}\}/";
$result = preg_grep($regExp, array("Lorem {{ipsum}} dolor sit amet, {{consectetur}} adipiscing elit."));

but I get back the given string as result


Solution

  • You are using the wrong function, you should use preg_match_all().

    You should also use lazy instead of greedy matching to avoid the result being ipsum}} dolor sit amet, {{consectetur. You can do that by adding a ? after your quantifier:

    $regExp = "/\{\{([^)]+?)\}\}/";
                          ^ here
    preg_match_all($regExp, "Lorem {{ipsum}} dolor sit amet, {{consectetur}} adipiscing elit.",
                   $result);
    
    var_dump($result);
    

    A working example.