The best way to handle the Windows or Linux path section

I have two lines:

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

I managed to call this regular expression:

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

which will return

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

However i'm looking

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

those. trailing slashes not found in fixed arrays

+4
source share
4 answers

Why not just check the "/" 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)

+3
source

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

 preg_split('#(?<=)[/\\\]#', $string); 
+1
source
 $dirs = explode(DIRECTORY_SEPARATOR, $string); $dirs[0] .= DIRECTORY_SEPARATOR; 
+1
source

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

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

This replaces the backslash with a slash, truncates any 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 like the one you described above - the root of the path will not contain a slash - but in fact it is best represented in this way. This is because the root of the path (i.e. C:\ or '/') is actually not useful when saving with a slash. As a result of this, you can call implode('/', $pathParts); and get the right way back, while with your array you get an extra slash in the root. In addition, \Users\User\My Documents (without a drive letter) is still a valid path on Windows, it just implies the current working volume.

+1
source

All Articles