使用php preg_replace自动链接joomla中的预定义单词的功能

时间:2014-09-08 19:20:47

标签: php function hyperlink preg-replace joomla2.5

我正在使用Joomla / k2组件,我想自动链接文章中的某些关键字。我做了一些研究,并在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);

    }
}    
?>

我将此功能粘贴在joomla的k2模板中,位于item.php的$ this-&gt; item-&gt; maintext之上,最后是空白页。

我确信我做错了什么但是我找不到它是什么!请看一下我的代码,看看,谢谢。

1 个答案:

答案 0 :(得分:1)

您粘贴的代码中存在多个语法错误,这可能就是为什么它没有做任何事情。试试这个:

// 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>

您需要更改代码,以便将$some_text设置为页面内容。