<?php

/*
Plugin Name: nuzzaci External Links
Plugin URI: http://www.nuzzaci.co.uk/2007/08/23/18:04:25
Description: This plugin will look through your posts before they get displayed and either modify the existing class attribute or create a class attribute with the value external to all links that don't link within the current domain name. It will ignore all links without http:// and all links where the node is an image. This plugin doesn't touch the original image or the database.
Version: 0.1
Author: nico nuzzaci
Author URI: http://www.nuzzaci.co.uk
*/


function nuzzaciExternalLinks($content){
    
    
// Domain name
    
$domainName $_SERVER['HTTP_HOST'];
    
   
// The post content
   
$postContent $content;

   
// Search pattern to find links
   
$searchPattern "/<a(.*?)href\=[\"|'](.*?)[\"|'](.*?)>(.*?)<\/a>/";
    
    
// Search
    
preg_match_all($searchPattern $postContent$searchResults);

    
// Parse result
    
foreach($searchResults[0] as $id => $value){
        
$anchor             $searchResults[0][$id];
        
$beforeHref     $searchResults[1][$id];
        
$href             $searchResults[2][$id];
        
$afterHref         $searchResults[3][$id];
        
$anchorNode     $searchResults[4][$id];
        
        
// Exlude all links containing the domainname and all links without http://
        
if(ereg($domainName$href) || !ereg("http://"$href)){
            continue;
        }
        
        
// exlude all image that links
        
if(preg_match("/<img/"$anchorNode)){
            continue;
        }
        
        
$find $anchor;
        
$replace '<a'.$beforeHref.'href="'.$href.'"'.$afterHref.'>'.$anchorNode.'</a>';
        
        
// Add external to existing class="" or creates the class addtribute.
        
if(preg_match("/class\=[\"|']*[\"|']/"$replace)){
            
$replace preg_replace ("/class\=[\"|'](.*?)[\"|']/""class=\"$1 external\""$replace);
        }else{
            
$replace preg_replace ("/href\=[\"|'](.*?)[\"|']/""class=\"external\" href=\"$1\""$replace);
        }
        
        
$postContent str_replace($find$replace$postContent);
        
    }
   return 
$postContent;
}

add_filter('the_content''nuzzaciExternalLinks');

?>