1

Lets say I have these two directory paths:

"/www/website/news/old/"

"/www/library/js/"

I need a PHP function that would output a relative path from one directory to another. In this example it should output something like "../../../library/js/"

2 Answers 2

2

Following function would do the job:

function getRelativePath($source, $destination) {
    $sourceArray = [];
    preg_match_all('/([^\/]+)/', $source, $sourceArray);
    $destinationArray = [];
    preg_match_all('/([^\/]+)/', $destination, $destinationArray);
    
    $sourceArray = array_reverse($sourceArray[0]);
    $destinationArray = array_reverse($destinationArray[0]);
    
    $relative = [];
    $hasPath = false;
    foreach ($sourceArray as $path) {
        for ($i = 0; $i < count($destinationArray); $i++ ) {
            $to = $destinationArray[$i];
            if ($path == $to) {
                $hasPath = true;
                for ($j = $i - 1; $j >= 0 ; $j--)
                    $relative[] = $destinationArray[$j];
                break 2;    
            }
        }
        $relative[] = "..";
    }
    return $hasPath ? implode("/",$relative) . "/" : "NO PATH";
}
Sign up to request clarification or add additional context in comments.

Comments

1

Here is a simple function given the source and destination exist:

function getRelativePath($source, $destination)
{
    $paths =
        array_map(fn ($arg) => explode('/', realpath($arg)), func_get_args());
    return
        str_repeat('../', count(array_diff_assoc(...$paths))) .
        implode('/', array_diff_assoc(...array_reverse($paths)));
}

Nothing fancy. No check is implemented on the source being a folder and not a file.

Note: the destination can be a file while the source is supposed to be a directory from where the relative path is calculated.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.