PHP:如何解析相对 url [英] PHP: How to resolve a relative url

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

问题描述

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

I need a function that given a relative URL and a base returns an absolute URL. I've searched and found many functions that do it different ways.

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

有规范的方法吗?

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

On this site I see great examples for python and c#, lets get a PHP solution.

推荐答案

也许这篇文章能帮上忙?

Perhaps this article could help?

http://nashruddin.com/PHP_Script_for_Converting_Relative_to_Absolute_URL

为方便起见,在下面复制了代码

reproduced code below for convenience

<?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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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