4

我试图弄清楚如何将“外部相对路径”转换为绝对路径:我真的很想要一个可以执行以下操作的函数:

$path = "/search?q=query";
$host = "http://google.com";
$abspath = reltoabs($host, $path);

并让 $abspath 等于“ http://google.com/search?q=query ” 另一个例子:

$path = "top.html";
$host = "www.example.com/documentation";
$abspath = reltoabs($host, $path);

并让 $abspath 等于“ http://www.example.com/documentation/top.html

问题是它不能保证是那种格式,它可能已经是绝对的,或者完全指向不同的主机,我不太确定如何处理这个问题。谢谢。

4

3 回答 3

2

您应该尝试 PECL 函数 http_build_url http://php.net/manual/en/function.http-build-url.php

于 2010-05-21T09:46:47.767 回答
1

所以分三种情况:

  1. 正确的网址
  2. 无协议
  3. 没有协议也没有域

示例代码(未经测试):

if (preg_match('@^http(?:s)?://@i', $userurl))
    $url = preg_replace('@^http(s)?://@i', 'http$1://', $userurl); //protocol lowercase
//deem to have domain if a dot is found before a /
elseif (preg_match('@^[^/]+\\.[^/]+@', $useurl)
    $url = "http://".$useurl;
else { //no protocol or domain
    $url = "http://default.domain/" . (($useurl[0] != "/") ? "/" : "") . $useurl;
}

$url = filter_var($url, FILTER_VALIDATE_URL);

if ($url === false)
    die("User gave invalid url").
于 2010-05-20T02:15:37.530 回答
0

看来我已经解决了自己的问题:

function reltoabs($host, $path) {
    $resulting = array();
    $hostparts = parse_url($host);
    $pathparts = parse_url($path);
    if (array_key_exists("host", $pathparts)) return $path; // Absolute
    // Relative
    $opath = "";
    if (array_key_exists("scheme", $hostparts)) $opath .= $hostparts["scheme"] . "://";
    if (array_key_exists("user", $hostparts)) {
        if (array_key_exists("pass", $hostparts)) $opath .= $hostparts["user"] . ":" . $hostparts["pass"] . "@";
        else $opath .= $hostparts["user"] . "@";
    } elseif (array_key_exists("pass", $hostparts)) $opath .= ":" . $hostparts["pass"] . "@";
    if (array_key_exists("host", $hostparts)) $opath .= $hostparts["host"];
    if (!array_key_exists("path", $pathparts) || $pathparts["path"][0] != "/") {
        $dirname = explode("/", $hostparts["path"]);
        $opath .= implode("/", array_slice($dirname, 0, count($dirname) - 1)) . "/" . basename($pathparts["path"]);
    } else $opath .= $pathparts["path"];
    if (array_key_exists("query", $pathparts)) $opath .= "?" . $pathparts["query"];
    if (array_key_exists("fragment", $pathparts)) $opath .= "#" . $pathparts["fragment"];
    return $opath;
}

就我的目的而言,这似乎工作得很好。

于 2010-05-20T03:30:29.263 回答