There is no native function that does the opposite.
Pure-php implementation:
<?php
function getRelativePath( $path, $compareTo ) {
if ( substr( $path, -1 ) == '/' ) {
$path = substr( $path, 0, -1 );
}
if ( substr( $path, 0, 1 ) == '/' ) {
$path = substr( $path, 1 );
}
if ( substr( $compareTo, -1 ) == '/' ) {
$compareTo = substr( $compareTo, 0, -1 );
}
if ( substr( $compareTo, 0, 1 ) == '/' ) {
$compareTo = substr( $compareTo, 1 );
}
if ( strpos( $path, $compareTo ) === 0 ) {
$offset = strlen( $compareTo ) + 1;
return substr( $path, $offset );
}
$relative = array( );
$pathParts = explode( '/', $path );
$compareToParts = explode( '/', $compareTo );
foreach( $compareToParts as $index => $part ) {
if ( isset( $pathParts[$index] ) && $pathParts[$index] == $part ) {
continue;
}
$relative[] = '..';
}
foreach( $pathParts as $index => $part ) {
if ( isset( $compareToParts[$index] ) && $compareToParts[$index] == $part ) {
continue;
}
$relative[] = $part;
}
return implode( '/', $relative );
}
?>
Some tests forr phpunit:
<?php
static public function getRelativePathProvider( ) {
return array(
array(
'/srv/foo/bar',
'/srv',
'foo/bar',
),
array(
'/srv/foo/bar',
'/srv/',
'foo/bar',
),
array(
'/srv/foo/bar/',
'/srv',
'foo/bar',
),
array(
'/srv/foo/bar/',
'/srv/',
'foo/bar',
),
array(
'/srv/foo/bar',
'/srv/test',
'../foo/bar',
),
array(
'/srv/foo/bar',
'/srv/test/fool',
'../../foo/bar',
),
array(
'/srv/mad/xp/mad/model/static/css/uni-form.css',
'/srv/mad/xp/liria/',
'../mad/model/static/css/uni-form.css',
),
);
}
public function testGetRelativePath( $path, $compareTo, $expected ) {
$result = getRelativePath( $path, $compareTo );
$this->assertEquals( $expected, $result );
}
?>