Insert String Into Another String at Given Position using PHP

substr_replace function

<?php

function insertStringAtPosition(string $inputStr, string $strToInsert, int $pos): string
{
    return substr_replace($inputStr, $strToInsert, $pos, 0);
}

$result = insertStringAtPosition('1234567', '<-->', 3);
echo $result.PHP_EOL; // 123<-->4567

$result = insertStringAtPosition('1234567', '-->', 10);
echo $result.PHP_EOL; // 1234567-->

Leave a Comment

Cancel reply

Your email address will not be published.