getting absolute urls?

Discussion in 'PHP' started by Geraldm, Apr 7, 2007.

  1. #1
    Hi,

    I have an array of urls like so:

    
    $urls = array('http://domain.com/text/','index.php', 'http://otherdomain.com/','../page.php');
    PHP:
    How can I convert them to absolute urls using something like: http://domain.com/dir/ as the base URL so the output will be this:

    
    http://domain.com/text/
    http://domain.com/dir/index.php
    http://otherdomain.com/
    http://domain.com/page.php
    Code (markup):
    I've had a look on google but cannot find any relevant information on it. Can anyone help?

    Thanks,
    Gerald.
     
    Geraldm, Apr 7, 2007 IP
  2. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #2
    This should do it.

    
    $mainurl = 'http://www.example.com/';
    $cwd = 'http://www.example.com/dir/';
    
    $urls = array('http://domain.com/text/', 'index.php', './index.php', 'http://otherdomain.com/', '../page.php', '/test.php');
    
    foreach ($urls AS $key => $url)
    {
    	if (preg_match('/^https?:\/\//i', trim($url)))
    	{
    		continue;
    	}
    	
    	if ($url[0] == '/')
    	{
    		$urls[$key] = $mainurl . basename($url);
    	}
    	else if (preg_match('/^\.\//', $url) OR basename($url) == $url)
    	{
    		$urls[$key] = $cwd . basename($url);
    	}
    	else if (preg_match('/^\.\.\//', $url))
    	{
    		$dirs = explode('/', str_replace($mainurl, null, $cwd));
    		$dirsback = preg_match_all('/\.\.\//', $url, $dummy);
    
    		for ($i = 0; $i < $dirsback; $i++)
    		{
    			array_shift($dirs);
    		}
    		
    		$urls[$key] = $mainurl . implode('/', $dirs) . basename($url);
    	}
    }
    
    print_r($urls);
    
    
    
    PHP:
     
    nico_swd, Apr 7, 2007 IP
  3. Geraldm

    Geraldm Well-Known Member

    Messages:
    1,330
    Likes Received:
    97
    Best Answers:
    0
    Trophy Points:
    115
    #3
    Thanks nico_swd,
    It works great!

    Cheers ....
    Gerald :)
     
    Geraldm, Apr 9, 2007 IP