Samuel Bolduc
Samuel Bolduc

Reputation: 19173

Slashes and backslashes uniformity on UNIX / Windows

I'm writing a PHP class, and I want it to be cross-platform compatible. I need to explode a path to find a particular folder name. What do I choose for the delimiter? The path will contain '/' on UNIX and '\' on Windows.

In this particular example, I want to get the name of the directory where an included file is stored. I use this :

private function find_lib_dir() {
    $array_path = explode('/', __DIR__);
    return $array_path[count($array_path)-1];
}

In this situation (and more generally), what can I do to make sure it will work on both Windows and UNIX?

Thanks!

Upvotes: 7

Views: 1790

Answers (4)

Supericy
Supericy

Reputation: 5896

I would do something like this:

private function find_lib_dir() {
    // convert windows backslashes into forward slashes
    $dir = str_replace("\\", "/", __DIR__);

    $array_path = explode('/', $dir);
    return $array_path[count($array_path)-1];
}

For your particular example, you could do what the other answers provided. However, if you are building strings yourself like:

__DIR__ . '/path/to/dir';

And then try to explode it, then you will have issues on UNIX vs Windows systems. In this situation, it would be best (imo) to replace all the backslashes to forward slashes (which is supported on both systems). And then explode based on forward slash.

Upvotes: 1

Nir Alfasi
Nir Alfasi

Reputation: 53525

You can use DIRECTORY_SEPARATOR as follows:

$array_path = explode(DIRECTORY_SEPARATOR, __DIR__);

Upvotes: 10

hek2mgl
hek2mgl

Reputation: 157947

You should use the DIRECTORY_SEPARATOR constant

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798486

Use basename() and dirname() for path manipulation instead of parsing it yourself.

Upvotes: 2

Related Questions