Question

How can I determine if a file path is absolute? Must work on both Windows and Linux.

Was it helpful?

Solution

Here my try at doing it with a single function:

function isAbsolutePath($path) {
    if (!is_string($path)) {
        $mess = sprintf('String expected but was given %s', gettype($path));
        throw new \InvalidArgumentException($mess);
    }
    if (!ctype_print($path)) {
       $mess = 'Path can NOT have non-printable characters or be empty';
       throw new \DomainException($mess);
    }
    // Optional wrapper(s).
    $regExp = '%^(?<wrappers>(?:[[:print:]]{2,}://)*)';
    // Optional root prefix.
    $regExp .= '(?<root>(?:[[:alpha:]]:/|/)?)';
    // Actual path.
    $regExp .= '(?<path>(?:[[:print:]]*))$%';
    $parts = [];
    if (!preg_match($regExp, $path, $parts)) {
        $mess = sprintf('Path is NOT valid, was given %s', $path);
        throw new \DomainException($mess);
    }
    if ('' !== $parts['root']) {
        return true;
    }
    return false;
}

I took this from one of my project you might find useful while working with files and paths: dragonrun1/file_path_normalizer

OTHER TIPS

Here's what I've come up with:

function is_absolute_path($path) {
    if($path === null || $path === '') throw new Exception("Empty path");
    return $path[0] === DIRECTORY_SEPARATOR || preg_match('~\A[A-Z]:(?![^/\\\\])~i',$path) > 0;
}

I think that covers all the possible root paths for Windows.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top