【问题标题】:php convert ../ into full pathphp 将 ../ 转换为完整路径
【发布时间】:2018-10-15 18:53:33
【问题描述】:

我想将../ 转换为完整路径。例如我在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;
        }    
    }

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

【问题讨论】:

标签: php regex


【解决方案1】:

一个简单的想法:

  • 使用 url 构建一个文件夹数组
  • 当(路径的)文件夹为..时,弹出数组的最后一项
  • 当它是.时,什么都不做
  • 对于其他文件夹,推送它们。

然后你只需要用/ 加入文件夹数组,并在前面加上方案和域。

$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

【讨论】:

    猜你喜欢
    • 2017-03-16
    • 1970-01-01
    • 2013-06-29
    • 2014-10-29
    • 2012-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多