【问题标题】:regex help, find first 3 occurrences of a keyword and str_ireplace the content正则表达式帮助,查找关键字的前 3 次出现并 str_ireplace 内容
【发布时间】:2011-05-02 01:02:36
【问题描述】:

给定一个文本块,我需要解析它是否存在关键字。然后,在关键字第一次出现时,我需要在它周围加上粗体标签(如果还没有的话),在关键字第二次出现时,斜体,第三次,下划线。

使用关键字“help”的示例:

这是一些带有关键字“帮助”的文本。如果你能提供帮助,我真的很感激。谢谢您的帮助!如果关键字 help 出现更多,我将忽略它们。

将被改写为...

这是一些带有关键字“help”的文本。如果你能帮助,我真的很感激。感谢您的帮助!如果关键字 help 出现更多,我将忽略它们。

【问题讨论】:

    标签: php regex string text-parsing


    【解决方案1】:

    我假设您需要基于 PHP 的解决方案,因为您提到了 str_ireplace

    您可以使用preg_replace_callback 来实现。
    此函数类似于preg_replace,但调用了一个用户定义的回调函数,其返回值将用于替换。

    为了跟踪出现次数,我在回调函数中使用了static 变量。

    $keyword = 'help';
    
    // the callback function
    function fun($matches)
    {
            static $count = 0;
    
            // switch on $count and later increment $count.
            switch($count++) {
                    case 0: return '<b>'.$matches[1].'</b>';   // 1st time..use bold
                    case 1: return '<em>'.$matches[1].'</em>'; 
                    case 2: return '<u>'.$matches[1].'</u>';
                    default: return $matches[1];              // don't change others.
            }
    }
    
    // search for keyword separated by word boundaries.
    // if present call the callback function.
    $text = preg_replace_callback("/\b($keyword)\b/","fun",$text);
    

    Code In Action

    【讨论】:

    • 感谢 codaddict!像魅力一样工作!
    • @coaddict,这很好用,但有一个例外:它不考虑关键字是否出现在 h1、h2、img(作为 alt 属性)等 html 标签内(我知道那是不是我原来的要求?)任何想法如何改变它以跳过包含在命名标签中的关键字?
    • 例子:如果预解析的内容是“This is a test post string并且关键字是”test post”,它会导致像这样的强标签加倍(下一个评论)...
    • 是一个测试帖字符串
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多