Last active
December 20, 2015 09:08
-
-
Save dhrrgn/6105175 to your computer and use it in GitHub Desktop.
A few handy functions for dealing with paths in PHP in a cross-platform environment.
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 | |
if ( ! defined('IS_WIN')) { | |
define('IS_WIN', (DIRECTORY_SEPARATOR === '\\')); | |
} | |
/** | |
* Normalizes and joins path segments in accordance with the current OS standard. | |
* | |
* Usage: | |
* | |
* join_path(__DIR__, 'foo', 'bar') | |
* join_path(array(__DIR__, 'bar')) | |
* | |
* @param string|array $first Either the first part of the path or an array of parts | |
* @return string The path. | |
*/ | |
function join_path($first) | |
{ | |
// We support both arrays or func args. | |
if (is_array($first)) { | |
$base = array_shift($first); | |
$parts = $first; | |
} else { | |
$base = $first; | |
$parts = func_get_args(); | |
array_shift($parts); | |
} | |
// We only want to rtrim the base because if it is an abs path on *nix | |
// it will have a leading slash. | |
$base = rtrim($base, '\\/'); | |
$parts = array_map(function ($p) { | |
return trim(str_replace(array('\\', '/'), DIRECTORY_SEPARATOR, $p), '\\/'); | |
}, $parts); | |
// Put the base back onto the front | |
array_unshift($parts, $base); | |
return implode(DIRECTORY_SEPARATOR, $parts); | |
} | |
/** | |
* Determines if the path given is an absolute path. | |
* | |
* @param string $path The path to check. | |
* @return boolean Whether it is an abs path. | |
*/ | |
function is_abs($path) | |
{ | |
if (IS_WIN) { | |
return ($path[1] === ':'); | |
} | |
return ($path[0] === '/'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment