【问题标题】:PHP replace keywords in string with href linkPHP用href链接替换字符串中的关键字
【发布时间】:2012-05-29 04:08:23
【问题描述】:

我“今天早上很胖”,所以请原谅这个简单的问题 - 我有一系列关键字,例如array('keyword1','keyword2'....) 并且我有一串文本 - (有点像博客内容的长度,即不仅仅是几个词,但可能是 200-800 个词)在字符串中搜索关键字并将其替换为链接。所以在文本中'keyword 1'(作为纯文本)将变成<a href='apage'>keyword1</a>等等。

看到说今天早上很厚。

提前致谢。

【问题讨论】:

    标签: php preg-match str-replace


    【解决方案1】:

    典型preg_replace案例:

    $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.

    现在上面没有做一个非常“智能”的替换,因为href 不是匹配关键字的函数,而实际上你可能想要这样做。在此处查看preg_replace_callback 以获得更大的灵活性,或编辑问题并提供有关您的目标的更多信息。

    【讨论】:

    • 非常感谢我想要的,只是出于兴趣,有没有办法只在关键字第一次出现时“匹配”?
    • @RussellParrott:仅匹配 anyone 关键字的第一个实例是 simple。匹配each one关键字的第一个实例并不是那么简单;您要么需要在循环中对每个限制为 1 的关键字执行 preg_replace,要么(最好)使用 preg_replace_callback,“记住”哪些关键字已经匹配至少一次,然后返回关键字本身作为替换对于那些已经看过的人。
    【解决方案2】:

    为什么你会使用正则表达式而不是 str_replace() !?正则表达式有效,但它使这个极其简单的问题变得过于复杂。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-27
      • 2018-12-06
      • 2014-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多