/** * 绝对路径转成相对 路径 * $path相对于$base的相对路径 * @param string $base * @param string $path * 思路:去除共同部分 */ function rela_pos($base, $path) { $base = explode('/', trim($base,'/')); $path = explode('/', trim($path,'/')); $ln1 = count($base); $ln2 = count($path); if ($ln1 > $ln2) { $i = 0; foreach ($path as $k => $v) { if ($v == $base[$k]) { $i++; }else{ break; } } } else { $i = 0; foreach ($base as $k1 => $v1) { if ($v1 == $path[$k1]) { $i++; }else{ break; } } } array_splice($base, 0, $i); array_splice($path, 0, $i); //当前两个路径有相同的根目录 $b_len=count($base)-1; $st=''; for($j=0;$j<$b_len;$j++){ $st.='../'; } return $st.implode('/',$path); } $a = '/c/a/b/c/d/t/w/e.php'; $b = '/a/b/12/34/c.php'; $res=rela_pos($a,$b); var_dump($res);