LoginSignup
8
8

More than 5 years have passed since last update.

realpath関数の相対パス取得版

Posted at
function relativepath($dst) {
    switch (false) {
        case $src = getcwd():
        case $dst = realpath($dst):
        case $src = explode(DIRECTORY_SEPARATOR, $src):
        case $dst = explode(DIRECTORY_SEPARATOR, $dst):
        case $src[0] === $dst[0]:
            return false;
    }
    $cmp =
        DIRECTORY_SEPARATOR === '\\' ?
        'strcasecmp' :
        'strcmp'
    ;
    for (
        $i = 0;
        isset($src[$i], $dst[$i]) && !$cmp($src[$i], $dst[$i]); 
        ++$i
    );
    return implode(
        DIRECTORY_SEPARATOR,
        array_merge(
            array('.'),
            ($count = count($src) - $i) ?
                array_fill(0, $count, '..') :
                array()
            ,
            array_slice($dst, $i)
        )
    );
}
8
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
8