I had to create something to what you need so here is the result. By giving a base directory you receive a relative path to a file starting from base directory. Function is pretty fast, 100,000 checks took 0.64s. on my server. And it works for both directories and files. It is linux compatible. Don't even try it on windows :)
/**
* Return a relative path to a file or directory using base directory.
* When you set $base to /website and $path to /website/store/library.php
* this function will return /store/library.php
*
* Remember: All paths have to start from "/" or "\" this is not Windows compatible.
*
* @param String $base A base path used to construct relative path. For example /website
* @param String $path A full path to file or directory used to construct relative path. For example /website/store/library.php
*
* @return String
*/
function getRelativePath($base, $path) {
// Detect directory separator
$separator = substr($base, 0, 1);
$base = array_slice(explode($separator, rtrim($base,$separator)),1);
$path = array_slice(explode($separator, rtrim($path,$separator)),1);
return $separator.implode($separator, array_slice($path, count($base)));
}
Usage
You need to get relative path to file /var/www/example.com/media/test.jpg
Your base path is /var/www/example.com
Use the function like this:
$relative = getRelativePath('/var/www/example.com','/var/www/example.com/media/test.jpg');
Function will return /media/test.jpg
.
If you need only the /media
part without a file use it like this:
$relative = dirname(getRelativePath('/var/www/example.com','/var/www/example.com/media/test.jpg'));