Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to join filesystem path strings in PHP?

Tags:

string

file

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.

like image 458
user89021 Avatar asked Jul 07 '09 08:07

user89021


People also ask

How to join path in PHP?

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.

Which of the following function is used to split file path in PHP?

So on further reflection, I started my solution using basename() . This returns the file name and extension for a given file path. From here, I used explode to split the base file name into it's file name and extension.


1 Answers

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' 
like image 55
Riccardo Galli Avatar answered Oct 05 '22 23:10

Riccardo Galli