Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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.
