1

I want to convert ../ into full paths.For example I have following urls in css in 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

I want to convert them into full path like below for above examples

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

I tried something like below

$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;
        }    
    }

I know am complicating it , There must be some easy way to this kind of operation.Please guide me .Thank you.

Gracie williams
  • 1,287
  • 2
  • 16
  • 39
  • I am creating Something like httrack using php , so base url wont help – Gracie williams May 05 '18 at 12:36
  • 1
    not sure if this help, or else, try the following query "php convert relative to absolute url": https://stackoverflow.com/questions/4444475/transfrom-relative-path-into-absolute-url-using-php – ariefbayu May 05 '18 at 13:19
  • Possible duplicate of [How to get base URL with PHP?](https://stackoverflow.com/questions/2820723/how-to-get-base-url-with-php) – JohnnyDevNull May 05 '18 at 13:25

1 Answers1

2

A simple idea:

  • build an array of folders with the url
  • when the folder (of the path) is .., pop the last item of the array
  • when it is ., do nothing
  • For other folders, push them.

Then you only have to join the folder array with / and to prepend the scheme and the domain.

$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

Casimir et Hippolyte
  • 88,009
  • 5
  • 94
  • 125