Thursday, September 4, 2025
HomeLanguagesInsert string at specified position in PHP

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 );
?>


Output:

I am very happy today.
RELATED ARTICLES

Most Popular

Dominic
32261 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6626 POSTS0 COMMENTS
Nicole Veronica
11795 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11855 POSTS0 COMMENTS
Shaida Kate Naidoo
6747 POSTS0 COMMENTS
Ted Musemwa
7023 POSTS0 COMMENTS
Thapelo Manthata
6695 POSTS0 COMMENTS
Umr Jansen
6714 POSTS0 COMMENTS