PHP, Easiest way to find a relative path from an absolute path
let's say i have an absolute path : 开发者_Python百科/myproject/web/uploads/myfolder/myfile.jpg
i'm searching to determinate a relative path fom a part of the absolute path, like this:
<?php
echo relative_path('/myproject/web/uploads/myfolder/myfile.jpg', 'web/uploads');
// print "myfolder/myfile.jpg"
If I understand, you just want the part from the absolute path that is after the given part:
function relative_path($absolute, $part) {
$pos = strpos($absolute, $part);
return substr($absolute, $pos + strlen($part) + 1);
}
How about:
function relative_path ($absolute, $part) {
return (($rel = strstr($absolute, $part)) !== FALSE) ? ltrim(substr($rel, strlen($part)),'/') : FALSE;
}
Returns a string with the relative path (as described above) or FALSE
on failure.
This function is by no means fool proof, as any function that attempted to do the task you outlined above would be. Consider the following:
$absolute = "/dir/someplace/dir/someplace/somedir/file.ext";
$part = "dir/someplace";
// Returns "dir/someplace/somedir/file.ext" when you may in fact want "somedir/file.ext"
relative_path($absolute, $part);
I suspect what you really need to do here is to re-think what you are actually trying to do...
精彩评论