I am using Joomla/k2 component and I would like to automatically link certain keywords in articles. I did some research and came accross this function on http://coderzone.org/library/PHP-Auto-link-text-with-a-given-set-of_1085.htm
<?php
// 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);
}
}
?>
I pasted this function in my k2 template overide in joomla,just above $this->item->maintext in item.php and ended up with a blank page.
I am sure I have done something wrong but i cannot find out what it it! Please take a look at my code and see, thanks.
There are several syntax errors in the code you've pasted, which is probably why it's not doing anything. Try this:
// set the text here; I've put in some sample text.
$some_text = "<p>My favourite animals are cats and dogs, but I can't stand horses -- they suck!</p>";
// 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',
'horses' => 'http://alltheprettyhorses.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('/\b('.preg_quote($word).')\b/i','<a href="'.$rep_string.'">$1</a>',$some_text);
}
}
echo $some_text;
// returns <p>My favourite animals are cats and <a href="http://dogs.com">dogs</a>,
// but I can't stand <a href="http://alltheprettyhorses.com">horses</a> -- they suck!</p>
You'll need to alter the code so that $some_text
is set to the page contents.