Search and replace multiple values with multiple/different values in PHP5?

后端 未结 5 2239
日久生厌
日久生厌 2020-11-30 03:35

Is there an inbuilt PHP function to replace multiple values inside a string with an array that dictates exactly what is replaced with what?

For example:



        
5条回答
  •  感动是毒
    2020-11-30 04:00

    IN CASE some one is looking for replacing same strings with different values ( per occurence ).. Example, to replace all ## by numbers++ OR values from an array-

    $split_at = '##';
    $string = "AA ##  BB ##  CC ##  DD";
    $new_string = '';
    // echo $string;
    $replace_num = 1;
    $replace_arr = ['first' , 'second' , 'third'];
    $split_at_cnt = substr_count($string, $split_at);
    for ($split=0; $split <= $split_at_cnt; $split++)
    {
        $new_string .= str_replace('##', ($replace_num++)." : ".$replace_arr[$split], substr( $string, 0, strpos($string, $split_at)+strlen($split_at)));
        $string = substr($string, strpos($string, $split_at)+strlen($split_at));
    }
    
    echo $new_string;
    

提交回复
热议问题