PHP:如何解析相对网址

我需要一个函数,给定一个相对URL和一个基返回一个绝对URL。我搜索并发现了许多不同方式的功能。

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

有没有规范的方式?

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


答案 1

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

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;
    }
?>

答案 2

另一个解决方案,如果你已经使用GuzzleHttp

此解决方案基于 的内部方法。GuzzleHttp\Client

use GuzzleHttp\Psr7;

function resolve(string $uri, ?string $base_uri): string
{
    $uri = Psr7\uri_for($uri);

    if (isset($base_uri)) {
        $uri = Psr7\UriResolver::resolve(Psr7\uri_for($base_uri), $uri);
    }

    // optional: set default scheme if missing
    $uri = $uri->getScheme() === '' && $uri->getHost() !== '' ? $uri->withScheme('http') : $uri;

    return (string) $uri;
}

推荐