Table of contents

Insert string at specified position with PHP

PHP Jul 15, 2020 Viewed 5 Comments 0

Use PHP's substr_replace() method to insert a string into an existing string.  Refer to substr_replace api.


substr_replace ( mixed $string , mixed $replacement , mixed $start [, mixed $length ] ) : mixed

substr_replace() replaces a copy of string delimited by the start and (optionally) length parameters with the string given in replacement.



The input string.


The replacement string.


If start is non-negative, the replacing will begin at the start'th offset into string.

If start is negative, the replacing will begin at the start'th character from the end of string.


If given and is positive, it represents the length of the portion of string which is to be replaced. If it is negative, it represents the number of characters from the end of string at which to stop replacing. If it is not given, then it will default to strlen( string ); i.e. end the replacing at the end of string. Of course, if length is zero then this function will have the effect of inserting replacement into string at the given start offset.

Use it

We set the fourth parameter length of the substr_replace() method to 0.

$oldStr = "abcdefg";
$strToInsert = "123";
$pos = 3;
// In the third position of $oldStr, insert 123.
$newStr = substr_replace($oldStr, $strToInsert, $pos, 0);
echo $oldStr;   // abcdefg
echo $newStr;   // abc123defg
Updated Jul 15, 2020