PHP: fakepath() to clean up a file path

Needed a quick function to remove relative elements from a path. Similar to PHP's realpath() but doesn't require the file to exist on the local filesystem. This also works for URLs.

function fakepath($url) {
    $split = preg_split("|/|",$url);
    $first = substr($url,0,1);

    foreach ($split as $item) {
        if ($item === "." || $item === "") {
            // If it's a ./ then it's nothing (just that dir) so don't add/delete anything
        } elseif ($item === "..") {
            // Remove the last item added since .. negates it.
            $removed = array_pop($ret);
        } else {
            $ret[] = $item;
        }
    }

    // Rebuild the string
    $ret = join("/",$ret);

    // Remove dupe /
    $ret = preg_replace("!/+!","/",$ret);

    // Restore the double / after the HTTP:
    $ret = preg_replace("!(https?:/)!","$1/",$ret);

    if ($first === '/') {
        $ret = "/$ret";
    }

    return $ret;
}
Leave A Reply
All content licensed under the Creative Commons License