PHP str_replace() with a limit param?

前端 未结 5 1935
猫巷女王i
猫巷女王i 2020-12-17 18:38

str_replace replaces all occurrences of a word with a replacement.

preg_replace replaces occurrences of a pattern with a replacement and ta

5条回答
  •  粉色の甜心
    2020-12-17 19:36

    $str = implode($replace, explode($search, $subject, $count + 1));
    

    Quick PoC:

    $str =
    "To be, or not to be, that is the question:
    Whether 'tis Nobler in the mind to suffer
    The Slings and Arrows of outrageous Fortune,
    Or to take Arms against a Sea of troubles,
    And by opposing end them";
    
    /* Replace the first 2 occurrences of 'to' with 'CAN IT' in $str. */
    echo implode('CAN IT', explode('to', $str, 3));
    

    Output (emphasis added):

    To be, or not CAN IT be, that is the question:
    Whether 'tis Nobler in the mind CAN IT suffer
    The Slings and Arrows of outrageous Fortune,
    Or to take Arms against a Sea of troubles,
    And by opposing end them

    Note that this method is case sensitive.

提交回复
热议问题