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!
You can use DIRECTORY_SEPARATOR
as follows:
$array_path = explode(DIRECTORY_SEPARATOR, __DIR__);
Use basename()
and dirname()
for path manipulation instead of parsing it yourself.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With