PHP 相对路径 绝对路径 路径转换 realpath php把相对路径转换成绝对路径方法

* 相对路径 -> 绝对路径 realpath

 relative path
        $c_abs = realpath($ss_rel);
        if ($c_abs === false) {
            $i_rtn = -1;
        } else {
            $ss_rel = $c_abs;
            $i_rtn = 0;
        }
        $lpc++;
    } // while (count($sv_path)>0)
 
// normal ending
    if (0===$i_rtn) {
        $out_abs = $ss_rel;  // set converted path
    }
    return $i_rtn;
}
 
// test
$inDir = "/Users/Mch/Code/php/Directory";
is_dir($inDir) || mkdir($inDir, 0777, true);
 
$wd = __DIR__;
chdir($inDir);
 
$out = "";
echo sub_rel2abs("../../../eclipse-workspace/blog.zip", $out).PHP_EOL;
echo $out.PHP_EOL;
 
chdir($wd);
@rmdir($inDir);
?>

output:

0
/Users/Mch/eclipse-workspace/blog.zip

  这里直接realpath就可以了,为什么多此一举?

 

*  绝对路径 -> 相对路径

= count($a) || $j >= count($b)) {
            throw new Exception('$j out of range');
        }
        for ($i = $j; $i >= 0; $i--) {
            if (strcmp($b[$i], $a[$i])!==0) {
                return false;
            }
        }
        return true;
    };
    // 找到a,b数组元素相同的下标
    while (array_pop($a)) {
        $i = count($a)-1;
        if (isset($b[$i])) {
            if ($sliceEquals($a, $b, $i)) {
                break;
            }
        }
        array_push($d, "..");
    }
    // 从首个不同元素开始
    for ($i+=1; $i < count($b); $i++) {
        array_push($d, $b[$i]);
    }
    return ".".DIRECTORY_SEPARATOR.implode(DIRECTORY_SEPARATOR, $d);
}

// test linux

$rel = abs2rel('/Users/Mch/Code/php/Directory/abs2rel.php', '/Users/Mch/eclipse-workspace/');  // project.zip
// $rel = abs2rel('/Users/Mch/Code/php/Directory/abs2rel.php', '/Users/Mch/Code/php/Directory/rel2abs.php');
// $rel = abs2rel('/Users/Mch/Code/php/Directory/abs2rel.php', '/etc/hosts');
// $rel = abs2rel('/opt/nginx/conf/nginx.conf', '/Users/Mch/Code/php/Directory/abs2rel.php');
echo $rel.PHP_EOL;

// test windows

// test
/*
$rel = abs2rel("G:\\eclipse-workspace\\platform\\enso\\pom.xml", 
    "G:\\eclipse-workspace\\platform\\enso\\webapp\\ckeditor\\js\\require.js");
*/
$rel = abs2rel("G:\\eclipse-workspace\\platform\\enso\\webapp\\ckeditor\\js", 
    "G:\\eclipse-workspace\\platform\\enso\\pom.xml");
echo $rel.PHP_EOL;

你可能感兴趣的:(php)