PHP: Turn relative links into absolute ones?

Discussion in 'Programming/Scripts' started by xtothez, Apr 19, 2005.

  1. xtothez

    xtothez New Member

    Hi,

    does anyone know of a function to turn relative links in HTML code (<a href="..."></a>, <img src="...">, ...) into absolute links?

    Any help is appreciated.

    X
     
  2. tagammeer

    tagammeer New Member

    Try this function:

    PHP:
    function absolute_url($txt$base_url){
      
    $needles = array('href="''src="''background="');
      
    $new_txt '';
      if(
    substr($base_url,-1) != '/'$base_url .= '/';
      
    $new_base_url $base_url;
      
    $base_url_parts parse_url($base_url);

      foreach(
    $needles as $needle){
        while(
    $pos strpos($txt$needle)){
          
    $pos += strlen($needle);
          if(
    substr($txt,$pos,7) != 'http://' && substr($txt,$pos,8) != 'https://' && substr($txt,$pos,6) != 'ftp://' && substr($txt,$pos,9) != 'mailto://'){
            if(
    substr($txt,$pos,1) == '/'$new_base_url $base_url_parts['scheme'].'://'.$base_url_parts['host'];
            
    $new_txt .= substr($txt,0,$pos).$new_base_url;
          } else {
            
    $new_txt .= substr($txt,0,$pos);
          }
          
    $txt substr($txt,$pos);
        }
        
    $txt $new_txt.$txt;
        
    $new_txt '';
      }
      return 
    $txt;
    }
    $txt is your HTML code where you want to convert your relative links. Works like a charm for me! :)
     
  3. xtothez

    xtothez New Member

    Hey, that's a nice one. Does exactly what I need. :D

    Thanks, tagammeer (btw, what is "tagammeer"? Is that a name, or does it mean something? Just curious... :rolleyes: )
     
  4. tagammeer

    tagammeer New Member

    No, it's not a name, "Tag am Meer" is German for "a day at the beach". I hope it gets warmer soon... :cool:
     
  5. Leszek

    Leszek New Member

    Like for example PHP-QT.
     
  6. mmrs151

    mmrs151 New Member

    Some Example please

    Hi, if you can give me an example how to use this wonderfull piece of code...
     
  7. falko

    falko Super Moderator

    Code:
    $new_txt = absolute_url($txt, $base_url);
    where $txt holds the text that you want to modify and $base_url is the URL of the site.
     

Share This Page