Skip to content

Instantly share code, notes, and snippets.

@fuale
Created April 3, 2019 03:53
Show Gist options
  • Save fuale/b48474faed4143388359d5d29bc40ae5 to your computer and use it in GitHub Desktop.
Save fuale/b48474faed4143388359d5d29bc40ae5 to your computer and use it in GitHub Desktop.
<?php
if (!function_exists('path_resolve')) {
/**
* Converts parts of the file path to the correct full path.
* @param string ...$parts
* @return string|string[]|null
*/
function path_resolve(string ...$parts): string
{
return preg_replace('#/+#', DIRECTORY_SEPARATOR,
implode(DIRECTORY_SEPARATOR,
array_reduce($parts, function ($path, $part) {
$part !== '' && $path[] = $part;
return $path;
}, [])
));
}
}
echo path_resolve('one', 'two'); // one/two
echo path_resolve('one/', 'two'); // one/two
echo path_resolve('one/', '///two'); // one/two
echo path_resolve('one/', 'two.json'); // one/two.json
echo path_resolve('one/', '/two/', 'th'); // one/two/th
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment