开发者

Best way to handle splitting a Windows or Linux path

开发者 https://www.devze.com 2023-04-10 11:06 出处:网络
I have two Strings: C:\\Users\\Bob\\My Documents /Users/Bob/Documents I have managed to conjure this regex:

I have two Strings:

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

I have managed to conjure this regex:

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

that will return

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

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

However, I am looking for

Array
(
    [0] => C:\
    [1] => Users
    [2] => Bob
    [3] => My Documents
)
开发者_如何学JAVA
Array
(
    [0] => /
    [1] => Users
    [2] => Bob
    [3] => Documents
)

ie Trailing slashes not present in corrected arrays


Why not just check for "/" or "\" and then use explode with the appropriate delimiter?

<?php
$s1 = 'C:\\Users\\Bob\\My Documents';
$s2 = '/Users/Bob/Documents';

function mySplit($s) {
    if(strpos($s, '/') !== false) {
        $d = '/';
    }elseif(strpos($s,'\\') !== false) {
        $d = '\\';
    }else {
        throw new Exception('Valid delimiter not found.');
    }

    $ret = explode($d, $s);
    $ret[0] .= $d;

    return $ret;
}

echo '<pre>' . print_r(mySplit($s1),true) . '</pre>';
echo '<pre>' . print_r(mySplit($s2),true) . '</pre>';
?>

(Updated with a slightly tidier version)


$dirs = explode(DIRECTORY_SEPARATOR, $string);
$dirs[0] .= DIRECTORY_SEPARATOR;


With the following code you get what you want, but the first key will also be without the slash:

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


I know you have already accepted an answer but there is a very simple, one line solution to this problem that I use regularly, and I feel it needs to be posted here:

$pathParts = explode('/', rtrim(str_replace('\\', '/', $path)));

This replaces backslashes with forward slashes, trims any trailing slashes, and explodes. This can be done safely, since windows paths cannot contain forward slashes, and linux paths cannot contain backslashes.

The resulting array does not look exactly like the one you have described above - the root part of the path will not contain a slash - but it is actually better represented this way anyway. This is because the root of the path (i.e. the C:\ or '/') is not actually that useful when stored with the slashes. With the result of this, you can call implode('/', $pathParts); and get a valid path back, whereas with you array you would end up with an extra slash at the root. Also, \Users\User\My Documents (without the drive letter) is still a valid path on Windows, it just implies the current working volume.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号