Pages

Auto-link text with a given set of


Snippet Name: Auto-link text with a given set of
Description: This bit of code turns words from a list into links with a URL target taken from the "reserved word list". When using both singular and plural match words, make sure the plurals come before the singular version (i.e. 'dogs' and 'dog').

// list of keywords to auto-link 
// list plural forms first
$reserved_word_list = array (
 
 'dogs' => 'http://dogs.com', 
 'dog' => 'http://dogs.com', 
 'cat' => 'http://cats.com', 
 'kitten' => 'http://cats.com',
 'horse' => 'http://horses.com'
}
 
 
// search text string and auto-link the words
foreach($reserved_word_list as $word => $rep_string){
 
 if(strpos($some_text, $word)){
 
  // link the word
  $some_text = preg_replace('/(\s+)('.preg_quote($word).')/i','$1<a href="'.$rep_string.'">$2</a>',$some_text);
 
 }
}

No comments:

Post a Comment