<?xml version="1.0" encoding="windows-1252"?>
<node id="523679" title="Convert relative to absolute URL given a base URL, without modules" created="2006-01-17 01:07:54" updated="2006-01-16 20:07:54">
<type id="1980">
snippet</type>
<author id="114691">
Aristotle</author>
<data>
<field name="doctext">
</field>
<field name="snippetdesc">
&lt;p&gt;I wrote this mainly because someone asked how to do this in PHP. Turns out there is nothing in like the venerable [cpan://URI] module in all of PHP-dom (how pathetic is that for a language as web-centric as it?).&lt;/p&gt;

&lt;p&gt;First, I tried writing this with mostly string functions, but that was too painful, so I switched to doing it using regexes, even though they’re piss-poorly supported. After a while, my eyes glazed over, so I resorted to writing and debugging the code in Perl first, and then compiling it down to &lt;del&gt;machine code&lt;/del&gt; &lt;ins&gt;PHP&lt;/ins&gt;.&lt;/p&gt;

&lt;p&gt;I thought I’d post this byproduct here for posterity, in case someone needs it in some circumstance.&lt;/p&gt;

&lt;p&gt;Tests included, but I’m pretty sure they’re not extensive enough to be 100% confident in the code. Proceed at your discretion.&lt;/p&gt;</field>
<field name="snippetcode">
&lt;c&gt;
sub abs_url {
	my ( $relative, $base ) = @_;

	return $relative if $relative =~ m{ \A http:// }ix;

	my ( $host, $hostrelative_abs ) = $base =~ m{
		\A
		http:// # skip scheme
		([^/]*) # capture hostname
		/*      # skip front slashes
		(.*?)   # capture everything that follows, but
		[^/]*   # leave out the optional final non-directory component
		\z
	}ix;

	$hostrelative_abs = '' if $relative =~ m!^/!;

	my $abs_url = join '/', $host, $hostrelative_abs, $relative;

	# replace '//' or '/./' with '/'
	1 while $abs_url =~ s{ / \.? (?=/|\z) }{}x;

	# remove '/foo/..' (but be careful to skip '/../..')
	1 while $abs_url =~ s{ / (?!\.\.) [^/]+ / \.\. (?=/|\z) }{}x;

	return "http://$abs_url";
}
&lt;/c&gt;

&lt;c&gt;
use Test::More;
my @test = qw(
 /foo/bar.gif      http://www.example.com/baz/quux/    http://www.example.com/foo/bar.gif
 foo/bar.gif       http://www.example.com/baz/quux/    http://www.example.com/baz/quux/foo/bar.gif
 ../../bar.gif     http://www.example.com/baz/quux/    http://www.example.com/bar.gif
 foo/bar.gif       http://www.example.com/baz/quux     http://www.example.com/baz/foo/bar.gif
 ../foo/bar.gif    http://www.example.com/baz/quux     http://www.example.com/foo/bar.gif
 ../../foo/bar.gif http://www.example.com/baz/quux/qux http://www.example.com/foo/bar.gif
);
plan tests =&gt; @test / 3;
do { is abs_url( $test[0], $test[1] ), $test[2]; splice @test, 0, 3 } while @test;
&lt;/c&gt;</field>
</data>
</node>
