dth54864 2011-09-15 06:37 采纳率: 0%
浏览 5
已采纳

PHP用href链接替换字符串中的关键字

I am being "thick this morning" so please excuse this simple question - I have an array of keywords e.g. array('keyword1','keyword2'....) and I have a string of text - (bit like a blog content in length i.e. not just a few words but may be 200-800 words) what is the best way to search the string for the keywords and replace them with an href link. So in the text 'keyword 1' (as plain text) will become <a href='apage'>keyword1</a> and so on.

See said was being thick this am.

Thanks in adavance.

  • 写回答

2条回答 默认 最新

  • dongzaheng4449 2011-09-15 06:46
    关注

    Typical preg_replace case:

    $text = "There is some text keyword1 and lorem ipsum keyword2.";
    $keywords = array('keyword1', 'keyword2');
    
    $regex = '/('.implode('|', $keywords).')/i';
    
    // You might want to make the replacement string more dependent on the
    // keyword matched, but you 'll have to tell us more about it
    $output = preg_replace($regex, '<a href="apage">\\1</a>', $text);
    
    print_r($output);
    

    See it in action.

    Now the above doesn't do a very "smart" replace in the sense that the href is not a function of the matched keyword, while in practice you will probably want to do that. Look into preg_replace_callback for more flexibility here, or edit the question and provide more information regarding your goal.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改