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?
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);