php - add string at offset?

前端 未结 2 1787
不思量自难忘°
不思量自难忘° 2021-01-22 14:17

If I have a string like \"test\", I have characters from offset 0-3. I would like to add another string to this one at offset 6. Is there a simple PHP function that can do this?

2条回答
  •  死守一世寂寞
    2021-01-22 15:05

    Convert the string to an array, in the case where the offset is greater than the string length fill in the missing indexes with a padding character of your choice otherwise just insert the string at the corresponding array index position and implode the string array.

    Please see the function below:

    function addStrAtOffset($origStr,$insertStr,$offset,$paddingCha=' ')
    {
        $origStrArr = str_split($origStr,1);
    
        if ($offset >= count($origStrArr))
        {
            for ($i = count($origStrArr) ; $i <= $offset ; $i++)
            {
                if ($i == $offset) $origStrArr[] = $insertStr;
                else $origStrArr[] = $paddingCha;
            }
        }
        else
        {
            $origStrArr[$offset] = $insertStr.$origStrArr[$offset];
        }
    
        return implode($origStrArr);
    }
    
    echo addStrAtOffset('test','new',6);
    

提交回复
热议问题