繁体   English   中英

使用正则表达式php获取嵌套花括号之间的值

[英]get values between nested curly braces with regex php

我有带有嵌套花括号的模板代码,如下所示:

{code{attributes}}

我需要两个值:“ code ”和“ attributes ”,我该怎么做?

请尝试以下操作:

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

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

var_dump($matches);

输出:

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

编辑:如果属性是可选的,请尝试以下操作:

$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);

输出:

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) ""
  }
}

这可能有点过于笼统,但也许(\\ {。*?\\})可行吗?

通过txt2re测试

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM