php转换../到完整路径

时间:2018-05-05 12:09:12

标签: php regex

我想将../转换为完整路径。例如,我在https://example.com/folder1/folder2/style.css

中的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;
        }    
    }

我知道这很复杂,这种操作必须有一些简单的方法。请指导我。谢谢。

1 个答案:

答案 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;
}

demo