get values between nested curly braces with regex php
I have template codes with neste开发者_StackOverflowd curly braces like this:
{code{attributes}}
I want both values: 'code' and 'attributes', how do I do that?
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) ""
  }
}
This may be a bit too general, but perhaps (\{.*?\}) could work?
Tested via txt2re
 
         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论