Location: PHPKode > scripts > Inner Link Replacer > inner-link-replacer/innerlink_replacer.php
<?php

class InnerLinkReplacer {
	
	var $Text='';
	var $Tags=array();
	var $replaceItems=array();
	
	function _replaceItems($phrase,$explanation,$link='') {
		foreach(array(" "=>"&nbsp;",".",",","!","?",";","'") as $v1=>$v2) {
			if (is_int($v1)) $v1=$v2;
			$this->replaceItems[" $phrase${v1}"]=$link ? " <a href=\"$link\" title=\"$explanation\">$phrase</a>$v2" : " <acronym title=\"$explanation\">$phrase</acronym>$v2";
		}
	}
	
	function replaceContext($text,$glossaryItems) {

		$this->replaceItems=array();

	  foreach($glossaryItems as $v) {

			$link=$v[link];
			$phrase=$v[phrase];
			$explanation = str_replace('"',"'", $v[explanation]);
			$this->_replaceItems($phrase,$explanation,$link);

			$lphrase = strtolower($phrase);
			if ($lphrase!=$phrase) $this->_replaceItems($lphrase,$explanation,$link);

			$uphrase = strtoupper($phrase);
			if ($uphrase==$phrase) $this->_replaceItems($uphrase,$explanation,$link);
		} 

		if ($this->replaceItems) {
			$this->Text='';
			$this->Tags=array();
			$parser = xml_parser_create('utf-8');
			xml_parser_set_option($parser,XML_OPTION_SKIP_WHITE,1);
			xml_parser_set_option($parser,XML_OPTION_CASE_FOLDING,0);
			xml_set_object($parser,&$this);
			xml_set_element_handler($parser,"start_tag","end_tag");
			xml_set_character_data_handler($parser,"data");
			$xml='<?xml version="1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" [
<!ENTITY nbsp "&#160;"> 
<!ENTITY quot "&#34;">
<!ENTITY amp "&#38;#38;">
<!ENTITY lt "&#38;#60;">
<!ENTITY gt "&#62;">
<!ENTITY euro "&#8364;">
<!ENTITY laquo "&#171;">
<!ENTITY raquo "&#187;">
<!ENTITY agrave "&#224;">
]>
<html>'.$text.'</html>';
			
			if (!xml_parse($parser,$xml,true)) {
				$error = xml_get_error_code($parser);
				//die("xmlclient error: ($error) ".xml_error_string($error)."<br/>Line: ".xml_get_current_line_number($parser)."<br/>Col:".xml_get_current_column_number($parser));
			}
      else {
 			  if ($this->Text) $text=$this->Text;
      }
			xml_parser_free($parser);
		}

		return trim($text); 
	} 

	function start_tag($parser,$name,$attr) {
		if (strtolower($name)=='html') return;
		$this->Tags[]=strtolower($name);
		$this->Text.="<$name ";
		if ($attr) foreach($attr as $i=>$v) $this->Text.="$i=\"$v\" ";
		$this->Text.=">\r\n";
  }

	function end_tag($parser,$name) {
		if (strtolower($name)=='html') return;
		$this->Text.="</$name>";
		array_pop($this->Tags);
	}

	function data($parser,$text) {
		if (!$text) return;
		$tag=array_pop($this->Tags);
		if ($tag!='a' && $tag!='acronym') $text=trim(strtr(" $text ",$this->replaceItems));
		$this->Text.=$text;
		$this->Tags[]=$tag;
	}
}
?>
Return current item: Inner Link Replacer