将文本区域转换为数组并将缩进文本转换为 PHP 中的嵌套数组

Convert textarea to array and indented text to nested-arrays in PHP

我想从 PHP 中的 Form Textarea POST 获取文本输入并遍历每一行文本并创建一个包含文本的 PHP 数组。

问题是我想获取前面有 4 个空格缩进的文本行,并使这些行成为上述数组项下的子嵌套数组。

我目前不确定如何执行此操作,因此非常感谢您的任何想法。

// basic demo to show each line of textarea post
$text = $_POST['textarea'];
foreach(explode("\n", $text) as $line) {
    echo $line;
    echo '<br>';
}   

更新

到目前为止的想法可能与此类似......

$text = $_POST['textarea'];
$in_nested_array = false;
$array = array();
foreach(explode("\n", $text) as $line) {

    if($line is 4 spaces){
        $in_nested_array = true;
        $array[''][$line];
    }else{
        //if in nested array and new line is not nested, add to root array
        if($in_nested_array){

        }else{
            $in_nested_array = false;
            $array[] = $line;
        }

    }
}   

以4个空格分隔:

$txt = preg_split('/    +/', $text);

第一次尝试:

$str = <<<EOD
bar
    baz
        meh
        lol
            tuuut
moo
EOD;

function parse($lines, $depth = 0, $cur = 0)
{
    $retVal = array();

    for ($i = $cur; $i < count($lines); $i++)
    {
        $line = $lines[$i];
        $lDepth = strlen($line) - strlen(ltrim($line, " "));

        if ($lDepth == $depth)
        {
            $retVal[] = array("line" => ltrim($line, " "));
        } elseif ($lDepth == $depth + 4) {
            $children = parse($lines, $depth + 4, $i);
            $retVal[count($retVal) - 1]["children"] = $children;
            $i += count($children);
        }
    }

    return $retVal;
}

$lines = explode("\n", $str);
echo "<pre>";
print_r(parse($lines));

输出:

Array
(
    [0] => Array
        (
            [line] => bar
            [children] => Array
                (
                    [0] => Array
                        (
                            [line] => baz
                            [children] => Array
                                (
                                    [0] => Array
                                        (
                                            [line] => meh
                                        )

                                    [1] => Array
                                        (
                                            [line] => lol
                                            [children] => Array
                                                (
                                                    [0] => Array
                                                        (
                                                            [line] => tuuut
                                                        )

                                                )

                                        )

                                )

                        )

                )

        )

    [1] => Array
        (
            [line] => moo
        )

)