Created
December 7, 2019 00:07
-
-
Save stemar/bd4dceff1cea916517f7aaefda6861e3 to your computer and use it in GitHub Desktop.
Normalize a path in PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Normalize a path. | |
* | |
* Usage: path('./one/', '/two/', 'three/'); | |
* Result: "./one/two/three" | |
* @param array $parts | |
* @return string | |
*/ | |
function path(...$parts) { | |
$parts = array_filter($parts); | |
$first = rtrim(array_shift($parts), DIRECTORY_SEPARATOR); | |
$parts = array_map(function ($value) { | |
return trim($value, DIRECTORY_SEPARATOR); | |
}, $parts); | |
array_unshift($parts, $first); | |
return join(DIRECTORY_SEPARATOR, $parts); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment