Question

I have a string that represents a path to a directory. I want split the string if it is a unix type path or a ms-dos type path.

How can this be done?

For example:

<?php

$a = some_path1/some_path2/some_path3; // unix type path
$b = some_path1\some_path2\some_path3; // MS-DOS type path

$foo = preg_split("something", $a); // what regex can be used here?
    // the above should work with $a OR $b

?>
Was it helpful?

Solution

Your regex would be

preg_split('_[\\\\/]_', $a);

The backslashes are escaped once for the string and again for the regular expression engine.

Edit:

If you know what type of path you've got (for example you know it's of the type of the current OS) you can do:

preg_split('_' . preg_quote($pathSep, '_') . '_', $a)

You could use the constant DIRECTORY_SEPARATOR in place of $pathSep depending on your needs. This would solve the problem pointed out by @Alan Storm

OTHER TIPS

If you are trying to write portable code (Linux, Windows, Mac OS, etc) and if the separator is always the same as the separator of the server, you can do the following:

<?php
$url = 'what/ever/';
$urlExploded = explode(DIRECTORY_SEPARATOR, $url);
?>

http://www.php.net/manual/en/dir.constants.php

Use a pipe operator to match either a forward slash or a backslash:

$foo = preg_split("/\\\|\//", $a);

In this example, echo $foo[0] of $a will output some_path1 and echo $foo[0] of $b will also output some_path1.

EDIT: You should put quotes around the values that you set $a and $b to. Otherwise, your code will trigger an error.

First, it seems to me that preg_split is overkill here; just use explode with the path separator (which is faster, according to the PHP docs: http://us2.php.net/manual/en/function.preg-split.php ).

Maybe PHP has a way to find the path separator, similar to Python's os.sep, but I couldn't find it. However, you could do something like:

$os = PHP_OS;
if (stristr($os, "WIN")) { $sep = '\\'; } else { $sep = '/'; } #
$pathFields = explode($sep, $pathToFile);

Note that this assumes you're only going to run this on Windows or a Unix-like system. If you might run it on some other OS with a different path separator, you'll need to do extra checks to be sure you're on a *nix system.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top