Insert String at Specified Position in PHP

In PHP, you can insert a string at a specified position within another string using various methods. The most common approaches include string concatenation with substr() and the substr_replace() function.

Using String Concatenation with substr()

This method breaks the original string into two parts and concatenates the insert string between them

<?php
$originalString = "Hello World!";
$insertString = "beautiful ";
$position = 6;

$newString = substr($originalString, 0, $position) . $insertString . substr($originalString, $position);
echo $newString;
?>
Hello beautiful World!

The substr() function extracts portions before and after the specified position, then the dot operator concatenates all three parts together.

Using substr_replace() Function

The substr_replace() function provides a more direct approach for inserting strings at specific positions

<?php
$originalString = "Hello World!";
$insertString = "beautiful ";
$position = 6;

$newString = substr_replace($originalString, $insertString, $position, 0);
echo $newString;
?>
Hello beautiful World!

The fourth parameter 0 indicates that no characters should be removed before inserting the new string, making it a pure insertion operation.

Comparison

Method Readability Performance Use Case
String Concatenation Medium Good Simple insertions
substr_replace() High Better Direct insertion/replacement

Conclusion

Both methods effectively insert strings at specified positions. Use substr_replace() for cleaner, more readable code, or string concatenation when you need more control over the process.

Updated on: 2026-03-15T10:32:59+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements