gpt4 book ai didi

php - 将 URI 转换为 URL

转载 作者:可可西里 更新时间:2023-11-01 01:09:27 25 4
gpt4 key购买 nike

如果我知道当前站点路径,如何将 URI 转换为 URL?

考虑这些例子:

当前路径是:`http://www.site.com/aa/folder/page1.php

Uri: folder2/page.php

URI:/folder2/page.php


如果当前路径是:

`http://www.site.com/aa/folder/

`http://www.site.com/aa/folder

那时 URL 会是什么样子?

我知道这应该是简单明了的,但我无法在任何地方找到完整的答案(是的,我确实在 Google 上搜索过)

最佳答案

这是一段具有您需要的功能的代码: http://ca.php.net/manual/en/function.parse-url.php#76682

编辑:上面的链接函数用一个例子修改

<?php

var_dump(resolve_url('http://www.site.com/aa/folder/page1.php','folder2/page.php?x=y&z=a'));

var_dump(resolve_url('http://www.site.com/aa/folder/page1.php','/folder2/page2.php'));

function unparse_url($components) {
return $components['scheme'].'://'.$components['host'].$components['path'];
}

/**
* Resolve a URL relative to a base path. This happens to work with POSIX
* filenames as well. This is based on RFC 2396 section 5.2.
*/
function resolve_url($base, $url) {
if (!strlen($base)) return $url;
// Step 2
if (!strlen($url)) return $base;
// Step 3
if (preg_match('!^[a-z]+:!i', $url)) return $url;
$base = parse_url($base);
if ($url{0} == "#") {
// Step 2 (fragment)
$base['fragment'] = substr($url, 1);
return unparse_url($base);
}
unset($base['fragment']);
unset($base['query']);
if (substr($url, 0, 2) == "//") {
// Step 4
return unparse_url(array(
'scheme'=>$base['scheme'],
'path'=>$url,
));
} else if ($url{0} == "/") {
// Step 5
$base['path'] = $url;
} else {
// Step 6
$path = explode('/', $base['path']);
$url_path = explode('/', $url);
// Step 6a: drop file from base
array_pop($path);
// Step 6b, 6c, 6e: append url while removing "." and ".." from
// the directory portion
$end = array_pop($url_path);
foreach ($url_path as $segment) {
if ($segment == '.') {
// skip
} else if ($segment == '..' && $path && $path[sizeof($path)-1] != '..') {
array_pop($path);
} else {
$path[] = $segment;
}
}
// Step 6d, 6f: remove "." and ".." from file portion
if ($end == '.') {
$path[] = '';
} else if ($end == '..' && $path && $path[sizeof($path)-1] != '..') {
$path[sizeof($path)-1] = '';
} else {
$path[] = $end;
}
// Step 6h
$base['path'] = join('/', $path);

}
// Step 7
return unparse_url($base);
}

?>

关于php - 将 URI 转换为 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4526818/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com