4 april 2007

Convert relative urls into absolute

I was creating a php-function to convert relative urls into absolute urls. For example:

... href="/foo.php?bar=1" ...

should be replaced by

... href="http://www.example.net/foo.php?bar=1" ...

I took a while, so I share this function with you:

<?php
/**
 * Convert relative urls into absolute urls 
 *
 * @param    string    $prefix 
 * @param    string    $text 
 * @return    string 
 */
function relativeToAbsolute($prefix$text)
 {
 
// search for single quotes and replace them by double quotes $search = '\''; 
$replace '"'
$text str_replace($search$replace$text);
// replace relative urls by absolute (prefix them with $prefix)
$pattern '/href="(?!http|https|ftp|irc|feed|mailto)([\/]?)(.*)"/i';
$replace 'href="'.$prefix.'/$2"';
$text preg_replace($pattern$replace$text);
 
// return
return $text;
}
?>

Dit artikel gaat over: , , , , . Convert relative urls into absolute werd geschreven door Tijs.
Er zijn al 2 reacties.

Reacties

Erik Bauffman

Erik Bauffman schreef:
04/04/07

Uiteraard nog vatbaar voor uitbreidingen, vergeet anchors niet tys ;)

steve

steve schreef:
22/05/07

Im looking at the code, could you explain a bit more of an example usage. like how is it determine the absolute path.

thanks I know this was a tricky problem, well done.

Reageer velden gemarkeerd met een sterretje zijn verplicht

*