PDA

View Full Version : [PHP] Resolve a relative url from 1 file to another given the 2 files paths



senocular
November 14th, 2006, 10:46 AM
Using PHP, is there any way to easily resolve a relative url from one path to another?

EX:
file1: sub/file1.html
file2: file2.html
result (from file1): ../file2.html

I can parse it myself by going through the path and comparing the parts, but I was wondering if there was some other way or some method that did this automatically. Any ideas?

bwh2
November 14th, 2006, 11:05 AM
it's not perfect, but this would work.


<?php
$start = 'sub/file1.html';
$files = array(
'file2.html',
'sub/file3.html',
'sub/sub/sub/sub/file4.html'
);
preg_match_all( '/\//', $start, $levels );

echo $start.'<br />';
echo '<table border="1">';
foreach( $files as $file ) {
echo '<tr>';
echo '<td>'.$file.'</td>';
$file = str_repeat( '../', count($levels[0]) ).$file;
echo '<td>'.$file.'</td>';
echo '</tr>';
}
echo '</table>';

?>

senocular
November 14th, 2006, 11:17 AM
Thanks. Thats kind of what I'm doing now, but I was hoping for something a little cleaner.

bwh2
November 14th, 2006, 11:29 AM
i'll think about it. i've been in a regex mood lately, so maybe i can whip something up.

senocular
November 14th, 2006, 11:34 AM
regex really wouldn't be necessary. I was looking for something like overlooked_builtin_php_method(url1, url2) ;)

bwh2
November 14th, 2006, 11:47 AM
yeah, i suppose you're right. i don't know of any built in functionality like that.