Insert string at specified position in PHP
Given a sentence, a string and the position, the task is to insert the given string at the specified position. We will start counting the position form zero. See the examples below.
Input : sentence = ‘I am happy today.’
string = ‘very’
position = 4
Output :I amvery happy today.
Begin counting with 0. Start counting from the very first character till we reach
the given position in the given sentence.
Spaces will also be counted and then insert the given string at the specified position.Input : sentence = ‘I am happy today.’
string = ‘ very’
position = 4
Output : I am very happy today.
The idea is to use substr_replace()
<?php $sentence = 'I am happy today.'; $string = 'very '; $position = '5'; echo substr_replace( $sentence, $string, $position, 0 ); ?> |
I am very happy today.
Recommended Posts:
- Program to Insert new item in array on any position in PHP
- unordered_multimap insert() in C++ STL
- list insert() in C++ STL
- unordered_map insert in C++ STL
- unordered_set insert() function in C++ STL
- unordered_multiset insert() function in C++ STL
- PHP | Ds\Deque insert() Function
- PHP | Ds\Vector insert() Function
- PHP | Ds\Sequence insert() Function
- 2-3 Trees | (Search and Insert)
- How to insert line break before an element using CSS?
- MongoDB Python | Insert and Update Data
- Insert a node in Binary Search Tree Iteratively
- Java Servlet and JDBC Example | Insert data in MySQL
- How to insert an item into array at specific index in JavaScript?
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



