douai2499 2014-09-08 19:20 采纳率: 100%
浏览 242
已采纳

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

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.

  • 写回答

1条回答 默认 最新

  • dongshi2836 2014-09-08 19:47
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集