waterschaats
waterschaats

Reputation: 994

get values between nested curly braces with regex php

I have template codes with nested curly braces like this:

{code{attributes}}

I want both values: 'code' and 'attributes', how do I do that?

Upvotes: 2

Views: 3160

Answers (2)

Jong Bor Lee
Jong Bor Lee

Reputation: 3855

Try the following:

$a = '{code{attributes}}';
$matches = array();

preg_match('/\{(.+)\{(.+)\}\}/', $a, $matches);

var_dump($matches);

Output:

array(3) {
  [0]=>
  string(18) "{code{attributes}}"
  [1]=>
  string(4) "code"
  [2]=>
  string(10) "attributes"
}

Edit: if the attributes are optional, try the following:

$a = '{code{attributes}}';
$b = '{code}';

$regex = '/\{(.+?)(?:\{(.+)\})?\}/';

$matches = array();
preg_match_all($regex, $a, $matches);
var_dump($matches);

$matches = array();
preg_match_all($regex, $b, $matches);
var_dump($matches);

Output:

array(3) {
  [0]=>
  array(1) {
    [0]=>
    string(18) "{code{attributes}}"
  }
  [1]=>
  array(1) {
    [0]=>
    string(4) "code"
  }
  [2]=>
  array(1) {
    [0]=>
    string(10) "attributes"
  }
}
array(3) {
  [0]=>
  array(1) {
    [0]=>
    string(6) "{code}"
  }
  [1]=>
  array(1) {
    [0]=>
    string(4) "code"
  }
  [2]=>
  array(1) {
    [0]=>
    string(0) ""
  }
}

Upvotes: 5

canadiancreed
canadiancreed

Reputation: 1984

This may be a bit too general, but perhaps (\{.*?\}) could work?

Tested via txt2re

Upvotes: 0

Related Questions