当前位置 博文首页 > fareast_mzh的博客:PHP去掉路径中的 ./ ../ 相对路径,绝对路

    fareast_mzh的博客:PHP去掉路径中的 ./ ../ 相对路径,绝对路

    作者:[db:作者] 时间:2021-08-13 15:57

    Str.php

        private static function replaceChar($subject, $search, $replace) {
            for ($i = 0; isset($subject[$i]); $i++) {
                if ($subject[$i] == $search) {
                    $subject[$i] = $replace;
                }
            }
            return $subject;
        }
    
        private static function join(string $sep, array $arr) {
            if (empty($arr)) {return "";}
            $s = $arr[0];
            $n = count($arr);
            for ($i = 1; $i < $n; $i++) {
                $s .= $sep.$arr[$i];
            }
            return $s;
        }
    
        public static function absPath($path) {
            if (DIRECTORY_SEPARATOR === '/') {
                $root = "/";
            } else {
                $path = self::replaceChar($path, DIRECTORY_SEPARATOR, '/');
                $root = "";
            }
            $a = [];
            $el = "";
            $lastChar = '\0';
            for ($i = 0; isset($path[$i]); $i++) {
                if ($path[$i] == '.') {
                    if ($lastChar == '.') {
                        array_pop($a);
                    } else {
                        $el .= $path[$i];
                    }
                } else if ($path[$i] == '/') {
                    if ($lastChar != '.' && $el) {
                        array_push($a, $el);
                    }
                    $el = "";
                } else {
                    $el .= $path[$i];
                }
                $lastChar = $path[$i];
            }
            array_push($a, $el);
            $path = $root.self::join(DIRECTORY_SEPARATOR, $a);
    
            return $path;
        }

    ?

    windows环境 is_file 始终false, 中文名utf-8 需要转换为gb2312

    iconv("UTF-8","GB2312//IGNORE",$data);

    ?

    cs