Preg Replace - replace second occurance of a match

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

    You could use preg_split to split the text at the matches, apply the modifications, and then put everything back together:

    $parts = preg_split('/(example)/', $str, 7, PREG_SPLIT_DELIM_CAPTURE);
    if (isset($parts[3])) $parts[3] = ''.$parts[3].'';
    if (isset($parts[7])) $parts[7] = ''.$parts[7].'';
    if (isset($parts[13])) $parts[13] = ''.$parts[13].'';
    $str = implode('', $parts);
    

    The index formula for the i-th match is index = i · 2 - 1.

提交回复
热议问题