我发现当 href src 和 base url 开始变得更加复杂时,接受的答案解决方案对我不起作用。
例如:
基本网址:
http://www.journalofadvertisingresearch.com/ArticleCenter/default.asp?ID=86411&Type=Article
参考资料来源:
/ArticleCenter/LeftMenu.asp?Type=文章&FN=&ID=86411&Vol=&No=&Year=&Any=
错误返回:
/ArticleCenter/LeftMenu.asp?Type=文章&FN=&ID=86411&Vol=&No=&Year=&Any=
我发现下面的函数正确返回了 url。我从这里的评论中得到了这个:来自 Isaac Z. Schlueter的http://php.net/manual/en/function.realpath.php 。
这正确返回:
http://www.journalofadvertisingresearch.com/ArticleCenter/LeftMenu.asp?Type=Article&FN=&ID=86411&Vol=&No=&Year=&Any=
function resolve_href ($base, $href) {
// href="" ==> current url.
if (!$href) {
return $base;
}
// href="http://..." ==> href isn't relative
$rel_parsed = parse_url($href);
if (array_key_exists('scheme', $rel_parsed)) {
return $href;
}
// add an extra character so that, if it ends in a /, we don't lose the last piece.
$base_parsed = parse_url("$base ");
// if it's just server.com and no path, then put a / there.
if (!array_key_exists('path', $base_parsed)) {
$base_parsed = parse_url("$base/ ");
}
// href="/ ==> throw away current path.
if ($href{0} === "/") {
$path = $href;
} else {
$path = dirname($base_parsed['path']) . "/$href";
}
// bla/./bloo ==> bla/bloo
$path = preg_replace('~/\./~', '/', $path);
// resolve /../
// loop through all the parts, popping whenever there's a .., pushing otherwise.
$parts = array();
foreach (
explode('/', preg_replace('~/+~', '/', $path)) as $part
) if ($part === "..") {
array_pop($parts);
} elseif ($part!="") {
$parts[] = $part;
}
return (
(array_key_exists('scheme', $base_parsed)) ?
$base_parsed['scheme'] . '://' . $base_parsed['host'] : ""
) . "/" . implode("/", $parts);
}