【问题标题】:PHP - create a multidimensional array according to a string's delimitersPHP - 根据字符串的分隔符创建多维数组
【发布时间】:2015-06-07 14:45:39
【问题描述】:

我想拆分以下文本:

“一些文字 [aaa[b[c1][c2]d]e][test] 更多文字”

到嵌套数组中:

Array
(
    [0] => aaa[b[c1][c2]d]e
    [1] => Array
        (
            [0] => b[c1][c2]d
            [1] => Array
                (
                    [0] => c1
                    [1] => c2
                )

        )

    [2] => test
)

php 手册中的“recursiveSplit”函数可以很好地显示结果。

函数如下:

function recursiveSplit($string, $layer) {
    preg_match_all("#\[(([^\[\]]*|(?R))*)\]#", $string, $matches);
    // iterate thru matches and continue recursive split
    if (count($matches) > 1) {
        for ($i = 0; $i < count($matches[1]); $i++) {
            if (is_string($matches[1][$i])) {
                if (strlen($matches[1][$i]) > 0) {
                    echo "<pre>Layer ".$layer.":   ".$matches[1][$i]."</pre><br />";
                    recursiveSplit($matches[1][$i], $layer + 1);
                }
            }
        }
    }
}

recursiveSplit($string, 0);

显示如下:

Layer 0:   aaa[b[c1][c2]d]e

Layer 1:   b[c1][c2]d

Layer 2:   c1

Layer 2:   c2

Layer 0:   test

我无法修改函数以将结果放入数组甚至是简单的字符串。我完全被困住了。有什么想法吗?

【问题讨论】:

    标签: php recursion nested


    【解决方案1】:

    您只需将项目添加到结果数组而不是回显,还需要添加 recursiveSplit 调用结果,如下所示:

    <?php
    function recursiveSplit($string, $layer) {
        $result = array();
        preg_match_all("#\[(([^\[\]]*|(?R))*)\]#", $string, $matches);
        // iterate thru matches and continue recursive split
        if (count($matches) > 1) {
            for ($i = 0; $i < count($matches[1]); $i++) {
                if (is_string($matches[1][$i])) {
                    if (strlen($matches[1][$i]) > 0) {
                        $result[] = $matches[1][$i];
                        echo "<pre>Layer ".$layer.":   ".$matches[1][$i]."</pre><br />";
                        $rec = recursiveSplit($matches[1][$i], $layer + 1);
                        if ($rec) {
                            $result[] = $rec;
                        }
                    }
                }
            }
        }
        return $result;
    }
    $string = "some text [aaa[b[c1][c2]d]e][test] more text";
    $result = recursiveSplit($string, 0);
    print_r($result);
    

    【讨论】:

    • 它很有效,而且非常智能。感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-06
    • 2020-12-31
    • 1970-01-01
    • 1970-01-01
    • 2021-12-27
    • 1970-01-01
    相关资源
    最近更新 更多