2011-08-29 56 views

回答

5

尝试以下操作:

$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) "" 
    } 
} 
+0

太棒了!非常感谢!如果只有一个值,有没有办法输出? '{code}' – waterschaats

+0

是的,请参阅我的编辑。不过,正则表达式变得更加复杂。 –

+0

太好了,再次感谢! – waterschaats

0

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

通过测试txt2re

相关问题