-->

preg_split string to multidimensional array

2019-08-07 11:45发布

问题:

Hello just looking for some help as I've gotten stuck

I have two Strings:

C:\Users\Bob\My Documents
/Users/Bob/Documents

That gets put through

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

that returns

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

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

I need

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

                )

        )

)

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

                )

        )

)

And ultimately merged to

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

                )

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

                )

        )

)

(properly merged, not just appended, so if another string started with C:\Users\Dan Then dan would appear on the ?3rd? Dimension. array_merge_recursive() ? )

回答1:

Just take the arrays returned by preg_split() and build your tree structure out of them:

$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 ];
    }
}


回答2:

You're probably best off just using pathinfo()

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

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

I assume you're trying to map a *nix directory to a Windows one?