Insert a string at specified position in PHP
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<?php $string = 'The quick brown fox over the lazy dog'; $replace = 'jumps '; $pos = 20; $result = substr_replace($string, $replace, $pos, 0); echo $result; /* Output: The quick brown fox jumps over the lazy dog */ ?> |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<?php $string = 'The quick brown fox over the lazy dog'; $replace = 'jumps '; $pos = 20; $result = substr($string, 0, $pos) . $replace . substr($string, $pos); echo $result; /* Output: The quick brown fox jumps over the lazy dog */ ?> |
That’s all about inserting a string at the specified position in PHP.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)