Jarves\Tools::getRelativePath PHP Method

getRelativePath() public static method

Returns a relative path from $path to $current.
public static getRelativePath ( string $from, string $to ) : string
$from string
$to string relative to this
return string relative path without trailing slash
    public static function getRelativePath($from, $to)
    {
        $from = '/' . trim($from, '/');
        $to = '/' . trim($to, '/');
        if (0 === ($pos = strpos($from, $to))) {
            return substr($from, strlen($to) + ('/' === $to ? 0 : 1));
        }
        $result = '';
        while ($to && false === strpos($from, $to)) {
            $result .= '../';
            $to = substr($to, 0, strrpos($to, '/'));
        }
        return !$to ? $result . substr($from, 1) : $result . substr($from, strlen($to) + 1);
    }

Usage Example

Beispiel #1
0
 public function testRelativePath()
 {
     $relative = Tools::getRelativePath('/anotherroot/web/file', '/root/web/other/dir');
     $this->assertEquals('../../../../anotherroot/web/file', $relative);
     $relative = Tools::getRelativePath('/root/web/file', '/root/web/other/dir');
     $this->assertEquals('../../file', $relative);
     $relative = Tools::getRelativePath('/root/web/dir/file/', '/root/web/dir');
     $this->assertEquals('file', $relative);
     $relative = Tools::getRelativePath('/root/web/other/file/', '/root/web/dir');
     $this->assertEquals('../other/file', $relative);
 }
All Usage Examples Of Jarves\Tools::getRelativePath