note 97885 deleted from function.realpath by peehaa
| From: | peehaa@php.net | Date: | Sun, 28 Apr 2019 09:47:40 +0000 |
| Subject: | note 97885 deleted from function.realpath by peehaa | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-210705@lists.php.net to get a copy of this message | ||
Note Submitter: jpic
----
There is no native function that does the opposite.
Pure-php implementation:
<?php
function getRelativePath( $path, $compareTo ) {
// clean arguments by removing trailing and prefixing slashes
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 );
}
// simple case: $compareTo is in $path
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',
),
);
}
/**
* @dataProvider getRelativePathProvider
*/
public function testGetRelativePath( $path, $compareTo, $expected ) {
$result = getRelativePath( $path, $compareTo );
$this->assertEquals( $expected, $result );
}
?>