使用 PHP 解析 URL 中的相对路径 [英] Resolve a relative path in a URL with PHP

查看:59
本文介绍了使用 PHP 解析 URL 中的相对路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例 1:domain.com/dir_1/dir_2/dir_3/./../../../
应该在浏览器中自然解析为 = domain.com/

示例 2:domain.com/dir_1/dir_2/dir_3/./../../../test/././../new_dir/
应该解析为 domain.com/new_dir/

示例 3:domain.com/dir_1/dir_2/dir_3/./../../../test/dir4/../final
应该解析为 domain.com/test/final

如何遍历字符串来执行此操作?我觉得 for() 循环此时会变得混乱.

How can I iterate through the string to do this? I feel like the for() loop would get confused at this point.

使用 PHP 将相对路径转换为绝对 URL 中提供的答案PHP:如何解析相对 url 不要在这种情况下对我有用.我不应该需要一个参考点(基础),因为目标是清理我已经拥有的东西.

The answers provided in Transform relative path into absolute URL using PHP and PHP: How to resolve a relative url don't work for me in this case. I shouldn't need a reference point (base), since the objective to clean up what I already have.

这不是 PHP - 失败的副本打开流:没有这样的文件或目录

推荐答案

这是一个比你想的更简单的问题.您需要做的就是在 / 字符上使用 explode(),并使用堆栈解析出所有单独的段.当您从左到右遍历数组时,如果看到 .,则什么都不做.如果您看到 ..,则从堆栈中弹出一个元素.否则,将一个元素压入堆栈.

This is a more simple problem then you are thinking about it. All you need to do is explode() on the / character, and parse out all of the individual segments using a stack. As you traverse the array from left to right, if you see ., do nothing. If you see .., pop an element from the stack. Otherwise, push an element onto the stack.

$str = 'domain.com/dir_1/dir_2/dir_3/./../../../';
$array = explode( '/', $str);
$domain = array_shift( $array);

$parents = array();
foreach( $array as $dir) {
    switch( $dir) {
        case '.':
        // Don't need to do anything here
        break;
        case '..':
            array_pop( $parents);
        break;
        default:
            $parents[] = $dir;
        break;
    }
}

echo $domain . '/' . implode( '/', $parents);

这将正确解析所有测试用例中的 URL.

This will properly resolve the URLs in all of your test cases.

请注意,错误检查留给用户作为练习(即当 $parents 堆栈为空并且您尝试从中弹出某些内容时).

Note that error checking is left as an exercise to the user (i.e. when the $parents stack is empty and you try to pop something off of it).

这篇关于使用 PHP 解析 URL 中的相对路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆