[英]PHP convert external relative path to absolute path
我試圖弄清楚如何將“外部相對路徑”轉換為絕對路徑:我真的很喜歡將執行以下操作的函數:
$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 ”
問題是它不能保證是那種格式,它可能已經是絕對的,或完全指向不同的主機,我不太確定如何處理這個問題。 謝謝。
你應該嘗試PECL函數http_build_url http://php.net/manual/en/function.http-build-url.php
所以有三種情況:
示例代碼(未經測試):
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").
看來我已經解決了我自己的問題:
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;
}
對於我的目的,這看起來效果很好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.