2017-05-09 30 views
1

我想將嵌套括號轉換爲包含關鍵字的數組。下面是模式:如何通過正則表達式將字符串分解爲數組元素?

preg_match_all('/(?=\{((?:[^{}]++|\{(?0)\})++)\})/', $string, $res); 

和數據需要分析:

employee { 
    cashier { salary = 100; } 
    technician { age = 44; } 
} 

結果,我需要:

Array 
    (
     [employee] => Array (
      [0] => Array 
       (
        [cashier] => Array 
         (
          [salary] => 100 
         ) 

       ) 

      [1] => Array 
       (
        [technician] => Array 
         (
          [age] => 44 
         ) 

       ) 
     ) 
    ) 

,但不能迭代內嵌套的括號內。困在這裏。在此先感謝您的幫助

+0

'preg_split'可能更合適 – RamRaider

回答

2

您需要在此處使用遞歸方法。

  1. 首先,用{}兩側分析外部結構。
  2. 看,如果我們能找到另一個嵌套結構
  3. 如果沒有,找key = value對並返回它們

一個正則表達式演示了外部結構上regex101.com發現,a complete PHP demo將如下所示:

<?php 

$string = <<<DATA 
employee { 
    cashier { salary = 100; } 
    technician { age = 44; } 
} 
DATA; 

// regular expressions  
$outer = '~(?P<key>\w+)\s*(?P<value>\{(?:[^{}]*|(?R))*\})~'; 

// inner, key = value 
$inner = '~(?P<key>\w+)\s*=\s*(?P<value>\w+)~'; 

function parse($string) { 
    global $outer, $inner; 
    $result = array(); 
    // outer 
    preg_match_all($outer, $string, $matches, PREG_SET_ORDER); 
    foreach ($matches as $match) { 
     $result[$match["key"]] = parse(
      substr($match["value"], 1, -1) 
     ); 
    } 

    // if not found, inner structure 
    if (!$matches) { 
     preg_match_all($inner, $string, $matches, PREG_SET_ORDER); 
     foreach ($matches as $match) { 
      $result[$match["key"]] = $match["value"]; 
     } 
     return $result; 
    } 
    return $result; 
} 

$result = parse($string); 
print_r($result); 
?> 


這產生了:

Array 
(
    [employee] => Array 
     (
      [cashier] => Array 
       (
        [salary] => 100 
       ) 

      [technician] => Array 
       (
        [age] => 44 
       ) 

     ) 

) 
+0

謝謝!有用! –

相關問題