'Replace values inside foreach loop and show only one string - PHP

I want to replace my values of string according to the position coming from JSON array. e.g. JSON has 0,3,6 numbers coming as offset(position) attribute. I want to get each value from my loop and make it replaceable inside my string. But Its getting only last value outside loop that is '6'(offset) and replacing 'c' with red color variable 'c'. Here's my code:

function str_replace_first($search, $replace, $subject)
    {
        $search = '/'.preg_quote($search, '/').'/';
        return preg_replace($search, $replace, $subject, 1);
    }

$str =  "we is chekin"; 
foreach ($json2['matches'] as $key=>$val) {
    $takeoffset = $val['offset'];    // getting offset value from JSON
    $convertingoffset = $str[$takeoffset]; //convert number to character
    $ofsetsplit = '<span style="color: red;">'.$convertingoffset.'</span>';  //value to replace
    $realone = $convertingoffset;    //value to be replaced
     $result_offset = str_replace_first($realone, $ofsetsplit, $str); //replacing
}
echo $result_offset; //getting result

When I replace inside loop:

enter image description here

When I replace outside loop, then only last value of position showing changed only enter image description here



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source