preg_split字符串到多维数组



你好,我被卡住了,正在寻求帮助

我有两个字符串:

C:UsersBobMy Documents
/Users/Bob/Documents

通过

preg_split('/(?<=[/\])(?![/\])/', $string)

返回

Array
(
    [0] => C:
    [1] => Users
    [2] => Bob
    [3] => My Documents
)
Array
(
    [0] => /
    [1] => Users/
    [2] => Bob/
    [3] => Documents
)

我需要

Array
(
    [C:] => Array
        (
            [Users] => Array
                (
                    [Bob] => Array
                        (
                            [My Documents] => array()
                        )
                )
        )
)
Array
(
    [/] => Array
        (
            [Users] => Array
                (
                    [Bob] => Array
                        (
                            [Documents] => array()
                        )
                )
        )
)

最终合并到

Array
(
    [C:] => Array
        (
            [Users] => Array
                (
                    [Bob] => Array
                        (
                            [My Documents] => array()
                        )
                )
        )
    [/] => Array
        (
            [Users] => Array
                (
                    [Bob] => Array
                        (
                            [Documents] => array()
                        )
                )
        )
)

(正确合并,而不仅仅是追加,所以如果另一个字符串以C:UsersDan开头,那么dan将出现在?3rd?Dimension.array_merge_recursive()?上(

只需取preg_split()返回的数组,并用它们构建树结构:

$tree = array();
foreach ( $strings as $string ) {
    $path = preg_split( '/(?<=[/\])(?![/\])/', $string );
    $ptr =& $tree;
    foreach ( $path as $elem ) {
        if ( ! array_key_exists( $elem, $ptr ) )
            $ptr[ $elem ] = array();
        $ptr =& $ptr[ $elem ];
    }
}

您最好使用pathinfo((

http://uk.php.net/manual/en/function.pathinfo.php

和realpath((http://uk.php.net/manual/en/function.realpath.php

我想你正试图将*nix目录映射到Windows目录?

相关内容

  • 没有找到相关文章

最新更新