str_replace() for multiple value replacement

后端 未结 6 1463
Happy的楠姐
Happy的楠姐 2020-12-03 10:30

Is there any possibility to use str_replace for multiple value replacement in a single line. For example i want to replace \' \' with \'-\'

6条回答
  •  我在风中等你
    2020-12-03 10:58

    Take note of the order of the arrays as it corresponds to the order. Like for below, A is replaced with B, B with C and so on.. so there you go.

    // Outputs F because A is replaced with B, then B is replaced with C, and so on...
    // Finally E is replaced with F, because of left to right replacements.
    $search  = array('A', 'B', 'C', 'D', 'E');
    $replace = array('B', 'C', 'D', 'E', 'F');
    $subject = 'A';
    echo str_replace($search, $replace, $subject);
    
    // Outputs: apearpearle pear
    // For the same reason mentioned above
    $letters = array('a', 'p');
    $fruit   = array('apple', 'pear');
    $text    = 'a p';
    $output  = str_replace($letters, $fruit, $text);
    echo $output;
    ?>
    

    source: PHP str_replace

提交回复
热议问题