In PHP, you can use the substr_replace() function to insert a string at a specified position within another string. To utilize this function, you'll need to determine the position of the substring where you want to insert the new string.
For instance, if you're using strpos to retrieve the position of a substring, you can proceed with the insertion using substr_replace(). The syntax for this function is as follows:
<code class="php">$newstr = substr_replace($oldstr, $str_to_insert, $pos, 0);</code>
In this code snippet, $pos represents the position in the $oldstr where you want to insert the $str_to_insert. The $pos parameter is referred to as the "offset" in the function's documentation.
As explained in the PHP documentation:
offset<br>If offset is non-negative, the replacing will begin at the offset'th offset into string.<br> If offset is negative, the replacing will begin at the offset'th character from the end of string.
This means that a non-negative $pos indicates the distance from the start of the string where the insertion should occur, while a negative $pos counts from the end of the string.
For example, the following code inserts the string "inserted" after the fifth character of the original string:
<code class="php">$oldstr = "Hello World!"; $pos = 5; $str_to_insert = "inserted"; $newstr = substr_replace($oldstr, $str_to_insert, $pos, 0); echo $newstr; // Output: Hello inserted World!</code>
The above is the detailed content of How to Insert Strings at Specific Positions in PHP?. For more information, please follow other related articles on the PHP Chinese website!