Home >Backend Development >PHP Tutorial >How to Insert a String at a Specific Position in PHP?
Often when working with strings, we need to insert a string at a specific position within another string. PHP provides a convenient function for this task: substr_replace().
Using substr_replace() to Insert a String
To insert a string at a specified position, use the following syntax:
<code class="php">$newstr = substr_replace($oldstr, $str_to_insert, $pos, 0);</code>
Understanding the Offset Argument
The $pos argument represents the offset within the original string where the insertion will occur. It can be either positive or negative:
For example, the following code inserts the string "test" at position 5 within the original string:
<code class="php">$oldstr = "Hello World!"; $newstr = substr_replace($oldstr, "test", 5, 0);</code>
Result:
Hello test World!
The above is the detailed content of How to Insert a String at a Specific Position in PHP?. For more information, please follow other related articles on the PHP Chinese website!