views:

1211

answers:

4

Is there a builtin function in php to intelligently join path strings?

Like path_join("abc/de/","/fg/x.php") which should return "abc/de/fg/x.php", but path_join("abc/de","fg/x.php") should have the same result

If not, is there a class availabel. Could also be valuable for splitting paths or removing parts of them. If you have written something maybe you can 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.

+5  A: 
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);
    }
    foreach ($paths as &$path) {
        $path = trim($path, '/');
    }
    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)

deceze
function pj($a,$b) { return rtrim($a, '/') .'/'. ltrim($b, '/'); }
+1  A: 

for getting parts of paths you can use pathinfo http://nz2.php.net/manual/en/function.pathinfo.php

for joining the response from @deceze looks fine

bumperbox
+1  A: 

Alternative using implode() and explode() functions

$a = '/a/bc/def/' ; $b = '/q/rs/tuv/path.xml';

$path = implode('/',array_filter(explode('/', $a . $b))) ;

echo $path; // -> a/bc/def/q/rs/tuv/path.xml

Chris J
A: 

@deceze's function doesn't keep the leading / when trying to join a path that starts with a unix absolute path e.g. joinPaths( '/var/www', '/vhosts/site' );

function unix_path() 
{
    $args = func_get_args();
    $paths = array();
    foreach( $args as $arg ) 
    {
        $paths = array_merge( $paths, (array)$arg );
    }
    foreach( $paths as &$path ) 
    {
        $path = trim( $path, '/' );
    }
    if( substr( $args[0], 0, 1 ) == '/' )
    {
        $paths[0] = '/' . $paths[0];
    }
    return join('/', $paths);
}
David Miller