loading

replace links - with $func parameter

This replaces html links passed to the function with the result of the specified function which takes the link location, the link contents and any attributes as arguments. <?php

 
function process_links($doc,$func){
  
$regmatches=array();
  
preg_match_all("/<a(.*?) href=[\"'](.+?)[\"'](.*?)>(.+?)<\/a>/"$doc$regmatches);
  foreach(
$regmatches[0] as $key => $data){
   
$doc=str_replace($regmatches[0][$key], call_user_func($func,$regmatches[2][$key], $regmatches[4][$key], $regmatches[1][$key] . $regmatches[3][$key]), $doc);
  }
  return 
$doc;
 }

 
// example:
 // (goes through a page and injects "class='external'" for all external links where a class name isn't already specified, for an IE-compatible way to format external links differently.

 
function process_ext_link($url,$inner,$extra){
  if ((
substr($url,0,5) == 'http:') && (strpos($extra,"class") === false)){
   return 
"<a href='" $url "' class='external'" $extra ">" $inner "</a>";
  } else {
   return 
"<a href='" $url "'" $extra ">" $inner "</a>";
  }
 }

 
$page process_links($page"process_ext_link");


?>
(unrated) | by defproc on March 26th, 2008 | adapts replace links by Jove

An account is required to post comments and adaptations

unsubscribe from human rights abuse in the war on terror

COMMENTS AND ADAPTATIONS

Should probably use single line mode, case insensitive in the regex. e.g. "/<a(.*?) href=[\"'](.+?)[\"'](.*?)>(.+?)<\/a>/si"

(1) | a comment by sproates on March 30th, 2008
challengebee.org | Powered by: Apache / PHP / MySQL | Made in Ninjapad NX | © defproc.co.uk, 2007_