-2

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

Iter Ator
  • 8,226
  • 20
  • 73
  • 164

2 Answers2

0

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.

jeroen
  • 91,079
  • 21
  • 114
  • 132
  • It's quite similar to my solution... Just a question: why do you need the [^)] part? Why do you want to exclude a closing parenthesis? – Tibor B. Nov 05 '14 at 16:14
  • @TiborB. Actually, you don't need it. In this case `.+?` would do just as well as `[^)]+?`. However, I assume the OP uses it for a reason so I copied his expression to avoid breaking other stuff we don't see here. – jeroen Nov 05 '14 at 16:16
  • Ahh, okay. I thought I was missing something. – Tibor B. Nov 05 '14 at 16:32
0

Use preg_match_all() instead of preg_grep

$str = 'Lorem {{ipsum}} dolor sit amet, {{consectetur}} adipiscing elit';
preg_match_all('!\{(\w+)\}!', $str, $m);
$result = array_map(function($v){return trim($v, '{}');},$m[0]);

print '<pre>';
print_r($result);
print '</pre>';
MH2K9
  • 11,951
  • 7
  • 32
  • 49