user89021 user89021 - 4 months ago 27
PHP Question

How to join filesystem path strings in PHP?

Is there a builtin function in PHP to intelligently join path strings? The function, given "abc/de/" and "/fg/x.php" as arguments, should return "abc/de/fg/x.php"; the same result should be given using "abc/de" and "fg/x.php" as arguments for that function.

If not, is there an available class? It could also be valuable for splitting paths or removing parts of them. If you have written something, may you share your code here?

It is ok to always use "/", I am coding for Linux only.

In Python there is

os.path.join()
, which is great.

Answer

Since this seems to be a popular question and the comments are filling with "features suggestions" or "bug reports"... All this code snippet does is join two strings with a slash without duplicating slashes between them. That's all. No more, no less. It does not evaluate actual paths on the hard disk nor does it actually keep the beginning slash (add that back in if needed, at least you can be sure this code always returns a string without starting slash).

join('/', array(trim("abc/de/", '/'), trim("/fg/x.php", '/')));

The end result will always be a path with no slashes at the beginning or end and no double slashes within. Feel free to make a function out of that.

EDIT: Here's a nice flexible function wrapper for above snippet. You can pass as many path snippets as you want, either as array or separate arguments:

function joinPaths() {
    $args = func_get_args();
    $paths = array();
    foreach ($args as $arg) {
        $paths = array_merge($paths, (array)$arg);
    }

    $paths = array_map(create_function('$p', 'return trim($p, "/");'), $paths);
    $paths = array_filter($paths);
    return join('/', $paths);
}

echo joinPaths(array('my/path', 'is', '/an/array'));
//or
echo joinPaths('my/paths/', '/are/', 'a/r/g/u/m/e/n/t/s/');

:o)

Comments