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 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 正弦信号发生器串并联电路电阻无法保持同步怎么办
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)