Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Slashes and backslashes uniformity on UNIX / Windows

Tags:

php

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!

like image 721
Samuel Bolduc Avatar asked Feb 01 '13 19:02

Samuel Bolduc


3 Answers

You can use DIRECTORY_SEPARATOR as follows:

$array_path = explode(DIRECTORY_SEPARATOR, __DIR__);
like image 120
Nir Alfasi Avatar answered Oct 18 '22 09:10

Nir Alfasi


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

like image 2
Ignacio Vazquez-Abrams Avatar answered Oct 18 '22 09:10

Ignacio Vazquez-Abrams


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.

like image 1
Supericy Avatar answered Oct 18 '22 10:10

Supericy