php 模拟返回url上一层目录

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/technofiend/article/details/77651580
    function parseUrl($url, $path)
    {
        if (preg_match('/^javascript/', $path)) {
            return $path;
        } else {
            if (strpos($path, '/') === 0) {
                $r      = parse_url($url);
                $newurl = $r['scheme'] . '://' . $r['host'];
                return parseUrl($newurl, ltrim($path, '/'));
            }

            $url = rtrim($url, '/') . '/';
            do {
                preg_match('/^(?<current>[^\/]*)(?<other>.*)$/', $path, $matches);
                if ($matches['current'] === '..') {
                    $explode = explode('/', $url);
                    if (count($explode) > 4) {
                        array_pop($explode);
                        array_pop($explode);
                        $url     = implode('/', $explode) . '/';
                    }
                } else if ($matches['current'] === '.') {
                    $explode = explode('/', $url);
                    if (count($explode) > 4) {
                        array_pop($explode);
                        $url     = implode('/', $explode) . '/';
                    }
                } else {
                    $url    .= $matches['current'] . '/';
                }

                $path = ltrim($matches['other'], '/');
            } while(!empty($matches['other']));

            return rtrim($url, '/');
        }
    }
    // 测试实例
    $url  = "http://jjx.com/hello/world/this/is";
    $path = '../../hello.html';
    echo parseUrl($url, $path);

猜你喜欢

转载自blog.csdn.net/technofiend/article/details/77651580