PHP:具有嵌套键/值语法到多维数组的字符串


PHP: String with nested key/value-syntax to multidimensional array

我正在寻找一个结合 php-recursion 的正则表达式,以将具有嵌套键/值语法的字符串解析为多维数组。有人知道我该如何完成这项工作吗?感谢任何帮助!

$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'
   )
  )
);

代码不干净,但请尝试一下,它对我有用:

<?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;
}