2016-12-07 52 views
0

你好我有2個父母(或更多...)塊和他們內部的許多子塊。在正則表達式中獲取父塊的內部

Block1 { 

    blockchild1 { 

    } 

    blockchild2 { 

    } 

    , ... 
} 

Block2 { 

    blockchild1 { 

    } 

    blockchild2 { 

    } 

    , ... 
} 

我想使用PHP的正則表達式,並得到首先家長塊內部

([a-z-0-9]*)\s*[{](.*?)[}] 

但這個表達式停止時到達第一childblock接近}首先意味着數據接收是

Block1 { 

    blockchild1 { 

    } 

但我想得到這樣的東西

array 1 = Block1 
array 2 = blockchild1 { 

    } 

    blockchild2 { 

    } 

    , ... 

我想通過正則表達式傳遞子塊[}]並獲得父母塊中的所有內容。我正則表達式是PCRE(PHP)

回答

0

你需要使用遞歸模式:

$pattern = '~(\w+)\s*{([^{}]*(?:{(?2)}[^{}]*)*)}~'; 

細節:

~ # delimiter 
(\w+) # capture group 1: block name 
\s* # eventual whitespaces 
{ 
( # capture group 2 
    [^{}]* # all that isn't a curly bracket 
    (?: 
     { (?2) } # reference to the capture group 2 subpattern 
     [^{}]* 
    )* 
) 
} 
~ 

請注意,對捕獲組2的引用位於捕獲組2本身內部,這就是爲什麼該模式是遞歸的。

0

試試這個:

$str = 'Block1 { 

    block1child1 { 

    } 

    block1child2 { 

    } 

    block1child3 { 

    } 
} 

Block2 { 

    block2child1 { 

    } 

    block2child2 { 

    } 

}'; 

$sub = '(\s*[a-z-0-9]*\s*{.*?}\s*)*'; 
preg_match_all("/([a-z-0-9]*)\s*{($sub)}/sim", $str, $matches, PREG_SET_ORDER); 

var_dump($matches); 

我使用的可變$sub澄清方法。它返回:

$matches[0][1] = 'Block1'; 
$matches[0][2] = ' 



block1child1 { 



} 



block1child2 { 



} 



block1child3 { 



} 

'; 

它包含塊2的右輸出(指數$matches1)。 此正則表達式不適用於子塊中的嵌套塊,並且不適用於塊內除父塊以外的任何其他內容。但是你沒有提到這一點。

這是online version

+0

無論如何。但我想讓所有內容不只是孩子們的塊 – Elh48

0
$str = 'Block1 { 

    block1child1 { 

    } 

    block1child2 { 

    } 

    block1child3 { 

    } 
} 

Block2 { 

    block2child1 { 

    } 

    block2child2 { 

    } 

}'; 

$str = preg_replace('([\w\d]+)', '"$0"', $str); 
$str = str_replace(' {', ': {', $str); 
$str = str_replace('}', '},', $str); 
$str = preg_replace('/\}\,[.\n]*?}/', '}}', $str); 


$str = json_decode('{' . substr($str, 0, strlen($str) - 1) . '}', true); 

var_export($str); 

array (
    'Block1' => 
    array (
    'block1child1' => 
    array (
    ), 
    'block1child2' => 
    array (
    ), 
    'block1child3' => 
    array (
    ), 
), 
    'Block2' => 
    array (
    'block2child1' => 
    array (
    ), 
    'block2child2' => 
    array (
    ), 
), 
) 
  1. 字符串轉換爲JSON
  2. 轉換JSON到數組