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

时间:2012-04-24 13:20:51

标签: php regex multidimensional-array nested

我正在寻找与php-recursion结合使用的正则表达式来解析带有嵌套键/值语法的字符串作为多维数组。有谁知道如何完成这项工作? THANX为任何帮助!

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

1 个答案:

答案 0 :(得分: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;
}