0

我正在搜索结合 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'
   )
  )
);
4

1 回答 1

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;
}
于 2012-04-24T14:43:09.260 回答