Php – 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.

Best Solution

function join_paths() {
    $paths = array();

    foreach (func_get_args() as $arg) {
        if ($arg !== '') { $paths[] = $arg; }

    return preg_replace('#/+#','/',join('/', $paths));

My solution is simpler and more similar to the way Python os.path.join works

Consider these test cases

array               my version    @deceze      @david_miller    @mark

['','']             ''            ''           '/'              '/'
['','/']            '/'           ''           '/'              '/'
['/','a']           '/a'          'a'          '//a'            '/a'
['/','/a']          '/a'          'a'          '//a'            '//a'
['abc','def']       'abc/def'     'abc/def'    'abc/def'        'abc/def'
['abc','/def']      'abc/def'     'abc/def'    'abc/def'        'abc//def'
['/abc','def']      '/abc/def'    'abc/def'    '/abc/def'       '/abc/def'
['','foo.jpg']      'foo.jpg'     'foo.jpg'    '/foo.jpg'       '/foo.jpg'
['dir','0','a.jpg'] 'dir/0/a.jpg' 'dir/a.jpg'  'dir/0/a.jpg'    'dir/0/a.txt'