2017-05-09 96 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

谢谢!有用! –

相关问题