note 97169 added to function.realpath

From: Date: Tue, 06 Apr 2010 10:41:21 +0000
Subject: note 97169 added to function.realpath
Groups: php.notes 
Request: Send a blank email to php-notes+get-167723@lists.php.net to get a copy of this message
# Function to get a relative path. # See tests for documentation function getRelativePath( $path, $compareTo ) { // clean arguments by removing trailing and prefixing slashes if ( substr( $path, -1 ) == DIRECTORY_SEPARATOR ) { $path = substr( $path, 0, -1 ); } if ( substr( $path, 0, 1 ) == DIRECTORY_SEPARATOR ) { $path = substr( $path, 1 ); } if ( substr( $compareTo, -1 ) == DIRECTORY_SEPARATOR ) { $compareTo = substr( $compareTo, 0, -1 ); } if ( substr( $compareTo, 0, 1 ) == DIRECTORY_SEPARATOR ) { $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( DIRECTORY_SEPARATOR, $path ); $compareToParts = explode( DIRECTORY_SEPARATOR, $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( DIRECTORY_SEPARATOR, $relative ); } # Test code for phpunit: static public function getRelativePathProvider( ) { return array( array( '/srv/foo/bar', # path '/srv', # compare to 'foo/bar', # expected result ), 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.78.225 ---- Manual Page -- http://www.php.net/manual/en/function.realpath.php Edit -- https://master.php.net/note/edit/97169 Del: integrated -- https://master.php.net/note/delete/97169/integrated Del: useless -- https://master.php.net/note/delete/97169/useless Del: bad code -- https://master.php.net/note/delete/97169/bad+code Del: spam -- https://master.php.net/note/delete/97169/spam Del: non-english -- https://master.php.net/note/delete/97169/non-english Del: in docs -- https://master.php.net/note/delete/97169/in+docs Del: other reasons-- https://master.php.net/note/delete/97169 Reject -- https://master.php.net/note/reject/97169 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#167723) next »