2012-04-24 58 views
0

我正在尋找一種結合php-recursion的正則表達式來將嵌套鍵/值語法的字符串解析爲多維數組。有沒有人有一個想法,我怎麼能做到這一點? THANX任何幫助!PHP:帶有嵌套鍵/值語法到多維數組的字符串

$string = "value1 | key2=value2 | [value3.1 | key3.2=value3.2 | key3.3=[key3.3.1=value3.3.1]]"; 

$result = parseSyntax($string); 

// RESULT 
//=============================================== 
array(
'0' => 'value1', 
'key2' => 'value2', 
'1' => array(
    '0' => 'value3.1', 
    'key3.2' => 'value3.2', 
    'key3.3' => array(
    'key3.3.1' => 'value3.3.1' 
    ) 
) 
); 
+0

開始[遞歸模式](http://php.net/manual/en/regexp.reference .recursive.php) – DaveRandom 2012-04-24 13:30:11

回答

0

的代碼是不是乾淨的,但嘗試它,它的工作對我來說:

<?php 

function parseSyntax($string) 
{ 
    // Get each parts in the string 
    $toparse = array(); 

    do 
    { 
     array_unshift($toparse, $string); 

     preg_match('/\[.+\]/', $string, $matches); 
     if(count($matches) > 0) { 
      $begin = strpos('[', $string)+1; 
      $end = strrpos(']', $string)-1; 
      $string = substr($matches[0], $begin, $end); 
     } 
    } 
    while(count($matches) > 0); 


    // Get data in an array for each part 
    $last = NULL; 
    $final = array(); 
    do 
    { 
     $toExplode = $toparse[0]; 
     if($last !== NULL) 
      $toExplode = str_replace ($last, '', $toparse[0]); 

     $result = array(); 
     $cells = explode(' | ', $toExplode); 
     foreach ($cells as $cell) { 
      $pairs = explode('=', $cell); 
      if(count($pairs) > 1) 
       $result[$pairs[0]] = $pairs[1]; 
      else 
       $result[] = $pairs[0]; 
     } 

     $last = $toparse[0]; 

     array_unshift($final, $result); 
     array_splice($toparse, 0, 1); 

    } 
    while(count($toparse) > 0); 


    // With each subarray, rebuild the last array 
    function build($arrays, $i = 0) 
    { 
     $res = array(); 
     foreach ($arrays[$i] as $key => $val) { 
      if($val == '[]') { 
       $res[$key] = build ($arrays, $i+1); 
      } else 
       $res[$key] = $val; 
     } return $res; 
    } 

    $final = build($final); 

    // Display result 
    return $final; 
}