我想将../
转换为完整路径。例如,我在https://example.com/folder1/folder2/style.css
img/example1.png
/img/example2.png
../img/example3.png
../../img/example4.png
https://example.com/folder1/folder2/example5.png
我希望将它们转换为如下所示的完整路径
https://example.com/folder1/folder2/img/example1.png
https://example.com/folder1/folder2/img/example1.png
https://example.com/folder1/img/example1.png
https://example.com/img/example1.png
https://example.com/folder1/folder2/example5.png
我尝试了类似下面的内容
$domain = "https://example.com";
function convertPath($str)
{
global $domain;
if(substr( $str, 0, 4 ) == "http")
{
return $str;
}
if(substr( $str, 0, 1 ) == "/")
{
return $domain.$str;
}
}
我知道这很复杂,这种操作必须有一些简单的方法。请指导我。谢谢。
答案 0 :(得分:2)
一个简单的想法:
..
时,弹出数组的最后一项.
时,什么都不做然后您只需要使用/
加入文件夹数组,并预先添加方案和域。
$url = 'https://example.com/folder1/folder2/style.css';
$paths = [ 'img/example1.png',
'/img/example2.png',
'../img/example3.png',
'../../img/example4.png',
'https://example.com/folder1/folder2/example5.png' ];
$folders = explode('/', trim(parse_url($url, PHP_URL_PATH), '/'));
array_pop($folders);
$prefix = explode('/' . $folders[0] . '/', $url)[0]; // need to be improved using parse_url to re-build
// properly the url with the correct syntax for each scheme.
function getURLFromPath($path, $prefix, $folders) {
if ( parse_url($path, PHP_URL_SCHEME) )
return $path;
foreach (explode('/', ltrim($path, '/')) as $item) {
if ( $item === '..' ) {
array_pop($folders);
} elseif ( $item === '.' ) {
} else {
$folders[] = $item;
}
}
return $prefix . '/' . implode('/', $folders);
}
foreach ($paths as $path) {
echo getURLFromPath($path, $prefix, $folders), PHP_EOL;
}