An elegant single-line PHP-inspired Python way to join the path.
This code does not use an unnecessary array.
Multi-platform
function os_path_join(...$parts) { return preg_replace('#'.DIRECTORY_SEPARATOR.'+#', DIRECTORY_SEPARATOR, implode(DIRECTORY_SEPARATOR, array_filter($parts))); }
Unix based systems
function os_path_join(...$parts) { return preg_replace('#/+#', '/', implode('/', array_filter($parts))); }
A Unix-based system without REST parameters (do not follow the explicit PEP8 philosophy):
function os_path_join() { return preg_replace('#/+#', '/', implode('/', array_filter(func_get_args()))); }
Usage
Usage
$path = os_path_join("", "/", "mydir/", "/here/");
Bonus: if you really want to follow Python os.path.join (). The first argument is required:
function os_path_join($path=null, ...$paths) { if (!is_null($path)) { throw new Exception("TypeError: join() missing 1 required positional argument: 'path'", 1); } $path = rtrim($path, DIRECTORY_SEPARATOR); foreach ($paths as $key => $current_path) { $paths[$key] = $paths[$key] = trim($current_path, DIRECTORY_SEPARATOR); } return implode(DIRECTORY_SEPARATOR, array_merge([$path], array_filter($paths))); }
Check the source of os.path.join () if you want: https://github.com/python/cpython/blob/master/Lib/ntpath.py
Warning: this solution is not suitable for URLs.
Samuel Dauzon Nov 02 '18 at 3:22 a.m. 2018-11-02 15:22
source share