본문 바로가기
프로그래밍/PHP

[PHP] 파일시스템에 접근하지 않고 realpath 와 같은 기능을 하는 함수

by 베리베리 2008. 8. 19.
Because realpath() does not work on files that do not
exist, I wrote a function that does.
It replaces (consecutive) occurences of / and \\ with
whatever is in DIRECTORY_SEPARATOR, and processes /. and /.. fine.
Paths returned by get_absolute_path() contain no
(back)slash at position 0 (beginning of the string) or
position -1 (ending)
<?php
   
function get_absolute_path($path
) {
       
$path = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $path
);
       
$parts = array_filter(explode(DIRECTORY_SEPARATOR, $path), 'strlen'
);
       
$absolutes
= array();
        foreach (
$parts as $part
) {
            if (
'.' == $part
) continue;
            if (
'..' == $part
) {
               
array_pop($absolutes
);
            } else {
               
$absolutes[] = $part
;
            }
        }
        return
implode(DIRECTORY_SEPARATOR, $absolutes
);
    }
?>

A test:
<?php
    var_dump
(get_absolute_path('this/is/../a/./test/.///is'
));
?>
Returns: string(14) "this/a/test/is"

As you can so, it also produces Yoda-speak. :)

댓글