This article demonstrates how to insert a string at the specified position in PHP.

1. Using substr_replace() function

The substr_replace() function replaces a portion of a string with another string. It takes the input string, the replacement string, the offset position, and the length, in that order, and replaces the input string delimited by the offset and length with the replacement string. If offset is non-negative, the replacement will begin at that position in the string. If the length is 0, then the replacement string is inserted into the input string at the given offset.

Download  Run Code

2. Using substr() function

The idea is to extract the substring before and after the specified position, and then concatenate the first part, replacement string, and second part together. You can use the substr() function to extract the part of a string specified by the offset and length parameters.

Download  Run Code

That’s all about inserting a string at the specified position in PHP.