Preg Replace - replace second occurance of a match

后端 未结 3 1890
佛祖请我去吃肉
佛祖请我去吃肉 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:36

    That's an interesting question. My implementation would be:

    function replace_exact($word, $tag, $string, $limit) {
        $tag1 = '<'.$tag.'>';
        $tag2 = '';
        $string = str_replace($word, $tag1.$word.$tag2, $string, 1);
        if ($limit==1) return $string;
        return str_replace($tag1.$word.$tag2,$word,$string,$limit-1);
    }
    

    Use it like this:

    echo replace_exact('Example', 'b', $source_text, 2);
    echo replace_exact('Example', 'i', $source_text, 4);
    

    I don't know about how fast this will work, but it will be faster than preg_replace.

提交回复
热议问题