PHP,从绝对路径中查找相对路径的最简单方法

PHP,从绝对路径中查找相对路径的最简单方法

问题描述:

let's say i have an absolute path : /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"

假设我有一条绝对路径: /myproject/web/uploads/myfolder/myfile.jpg p>

我正在寻找确定绝对路径的一部分的相对路径,如下所示: p>

 &lt;  ?php 
 
echo relative_path('/ myproject / web / uploads / myfolder / myfile.jpg','web / uploads'); 
 
 // print“myfolder / myfile.jpg”
  code>   pre> 
  div>

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...