note 97885 added to function.realpath

From: Date: Thu, 13 May 2010 19:04:31 +0000
Subject: note 97885 added to function.realpath
Groups: php.notes 
Request: Send a blank email to php-notes+get-169223@lists.php.net to get a copy of this message
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 ); } ?> ---- Server IP: 130.206.1.5 Probable Submitter: 87.223.74.210 ---- Manual Page -- http://www.php.net/manual/en/function.realpath.php Edit -- https://master.php.net/note/edit/97885 Del: integrated -- https://master.php.net/note/delete/97885/integrated Del: useless -- https://master.php.net/note/delete/97885/useless Del: bad code -- https://master.php.net/note/delete/97885/bad+code Del: spam -- https://master.php.net/note/delete/97885/spam Del: non-english -- https://master.php.net/note/delete/97885/non-english Del: in docs -- https://master.php.net/note/delete/97885/in+docs Del: other reasons-- https://master.php.net/note/delete/97885 Reject -- https://master.php.net/note/reject/97885 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#169223) next »