Preg Replace - replace second occurance of a match

后端 未结 3 1889
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-20 09:22

I am relatively new to php, and hope someone can help me with a replace regex, or maybe a match replace I am not exactly sure.

I want to automatically bold the (seco

3条回答
  •  孤城傲影
    2020-12-20 09:33

    The regular expression itself cannot count, and the preg_ functions provide little help. You need a workaround. If you were to actually search for just a word, you might want to use string functions. Otherwise try:

    // just counting
    if (7 >= preg_match_all($pattern, $subject, $matches)) {
    
       $cb_num = 0;
       $subject = preg_replace_callback($pattern, "cb_ibu", $subject);
    }
    
    function cb_ibu($match) {
        global $cb_num;
    
        $match = $match[0];
    
        switch (++$cb_num) {
            case 2: return "$match";
            case 4: return "$match";
            case 7: return "$match";
            default: return $match;
        }
    }
    

    The trick is to have a callback which does the accounting. And there it's quite easy to add any rules.

提交回复
热议问题