PHP:如何解析相对 URL

标签 php url relative-path resolveurl relative-url

我需要一个函数,它给定一个相对 URL 和一个返回绝对 URL 的基数。我搜索并发现了许多以不同方式执行此操作的函数。

resolve("../abc.png", "http://example.com/path/thing?foo=bar")
# returns http://example.com/abc.png

有规范的方法吗?

在这个网站上我看到了 python 和 c# 的很好的例子,让我们得到一个 PHP 解决方案。

最佳答案

也许这篇文章可以提供帮助?

http://nashruddin.com/PHP_Script_for_Converting_Relative_to_Absolute_URL

编辑:为方便起见,在下面复制代码

<?php
    function rel2abs($rel, $base)
    {
        /* return if already absolute URL */
        if (parse_url($rel, PHP_URL_SCHEME) != '' || substr($rel, 0, 2) == '//') return $rel;

        /* queries and anchors */
        if ($rel[0]=='#' || $rel[0]=='?') return $base.$rel;

        /* parse base URL and convert to local variables:
         $scheme, $host, $path */
        extract(parse_url($base));

        /* remove non-directory element from path */
        $path = preg_replace('#/[^/]*$#', '', $path);

        /* destroy path if relative url points to root */
        if ($rel[0] == '/') $path = '';

        /* dirty absolute URL */
        $abs = "$host$path/$rel";

        /* replace '//' or '/./' or '/foo/../' with '/' */
        $re = array('#(/\.?/)#', '#/(?!\.\.)[^/]+/\.\./#');
        for($n=1; $n>0; $abs=preg_replace($re, '/', $abs, -1, $n)) {}

        /* absolute URL is ready! */
        return $scheme.'://'.$abs;
    }
?>

关于PHP:如何解析相对 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1243418/

相关文章:

php - 计算未选中的复选框

php - Mongodb查询问题

php - 在 laravel 4 中生成相对于基本 url 的 url

MSBuild 干净目录字符串

css - 如何从 style.css 链接到 WordPress 插件文件夹?

php - 使 .htaccess 使用前端 Controller 重写对/web 的所有请求?

带有外键的 PHP MySQL 查询搜索

jquery - 如何在 Django 中发布 jQuery 后呈现上一页

php - 将搜索 URL 转换为 SeoFriendly URL

javascript - 图像的相对路径受到 routify 中嵌套路由的影响