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.
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.
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.
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'
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