Kamala - Credit Report - Military Loans - Debt Consolidation - Debt Consolidation

PDA

View Full Version : getting absolute urls?


Geraldm
Apr 7th 2007, 3:54 am
Hi,

I have an array of urls like so:


$urls = array('http://domain.com/text/','index.php', 'http://otherdomain.com/','../page.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

I've had a look on google but cannot find any relevant information on it. Can anyone help?

Thanks,
Gerald.

nico_swd
Apr 7th 2007, 5:27 am
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);

Geraldm
Apr 9th 2007, 4:27 am
Thanks nico_swd,
It works great!

Cheers ....
Gerald :)