PHP

realpath関数の相対パス取得版

More than 5 years have passed since last update.

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)
)
);
}