Search code examples
phpregexpreg-split

Best way to handle splitting a Windows or Linux path


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
)

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

ie Trailing slashes not present in corrected arrays


Solution

  • 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)