2011-08-29 81 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