我為我的一個專案編寫了一個函式,將相對 URL 轉換為絕對 URL。考慮到我在其他地方找不到它,我想我應該把它貼在這裡。
以下函式接收兩個參數,第一個參數是您要從相對 URL 轉換為絕對 URL 的 URL,第二個參數是絕對 URL 的範例。
目前它不會解析 URL 中的 '../',只是因為我不需要它。大多數網路伺服器會為您解析這個。如果您希望它解析路徑中的 '../',只需進行少量修改即可。
<?php
function relativeToAbsolute($inurl, $absolute) {
$absolute_parts = parse_url($absolute);
if ( (strpos($inurl, $absolute_parts['host']) == false) ) {
$tmpurlprefix = "";
if (!(empty($absolute_parts['scheme']))) {
$tmpurlprefix .= $absolute_parts['scheme'] . "://";
}
if ((!(empty($absolute_parts['user']))) and (!(empty($absolute_parts['pass'])))) {
$tmpurlprefix .= $absolute_parts['user'] . ":" . $absolute_parts['pass'] . "@";
}
if (!(empty($absolute_parts['host']))) {
$tmpurlprefix .= $absolute_parts['host'];
if (!(empty($absolute_parts['port']))) {
$tmpurlprefix .= ":" . $absolute_parts['port'];
}
}
if ( (!(empty($absolute_parts['path']))) and (substr($inurl, 0, 1) != '/') ) {
$path_parts = pathinfo($absolute_parts['path']);
$tmpurlprefix .= $path_parts['dirname'];
$tmpurlprefix .= "/";
}
else {
$tmpurlprefix .= "/";
}
if (substr($inurl, 0, 1) == '/') { $inurl = substr($inurl, 1); }
if (substr($inurl, 0, 2) == './') { $inurl = substr($inurl, 2); }
return $tmpurlprefix . $inurl;
}
else {
return $inurl;
}
}
$absolute = "http://" . "user:pass@example.com:8080/path/to/index.html"; echo relativeToAbsolute($absolute, $absolute) . "\n";
echo relativeToAbsolute("img.gif", $absolute) . "\n";
echo relativeToAbsolute("/img.gif", $absolute) . "\n";
echo relativeToAbsolute("./img.gif", $absolute) . "\n";
echo relativeToAbsolute("../img.gif", $absolute) . "\n";
echo relativeToAbsolute("images/img.gif", $absolute) . "\n";
echo relativeToAbsolute("/images/img.gif", $absolute) . "\n";
echo relativeToAbsolute("./images/img.gif", $absolute) . "\n";
echo relativeToAbsolute("../images/img.gif", $absolute) . "\n";
?>
輸出結果
http:// user:pass@example.com:8080/path/to/index.html
http:// user:pass@example.com:8080/path/to/img.gif
http:// user:pass@example.com:8080/img.gif
http:// user:pass@example.com:8080/path/to/img.gif
http:// user:pass@example.com:8080/path/to/../img.gif
http:// user:pass@example.com:8080/path/to/images/img.gif
http:// user:pass@example.com:8080/images/img.gif
http:// user:pass@example.com:8080/path/to/images/img.gif
http:// user:pass@example.com:8080/path/to/../images/img.gif
如果以上程式碼不是你喜歡的風格,或者你覺得它「雜亂」,或是你認為有更好的方法來完成它,請見諒。我盡可能地移除了空白。
歡迎改進 :)