Insert Characters in a String at a Certain Position using String Concatenation

One way to insert characters into a string is by splitting the string at the desired position, inserting the required string and then concatenating the parts with the new characters.

Example: Implementation of inserting characters in a string at a certain position using string concatenation.

PHP




<?php
// To perform string concatenation
function insertChars($str, $insert, $position) {
    return substr($str, 0, $position
        . $insert . substr($str, $position);
}
  
// Given Data
$str = "Hello World";
$insertStr = "Beautiful ";
$position = 6;
  
$newStr = insertChars($str, $insertStr, $position);
echo $newStr;
  
?>


Output

Hello Beautiful World

Time Complexity: O(1)
Auxiliary Space: O(1)

How to Insert Characters in a String at a Certain Position in PHP ?

In this article, you will learn how to insert characters into a string at a specific position in PHP. Given a string str and an integer position that describes the index in the original string where the desired string insertStr will be added. This can be achieved using various approaches, such as string concatenation, and the substr_replace() function.

Examples:

Input: 
str = "Welcome w3wiki"
insertStr = "to "
position = 8
Output: "Welcome to w3wiki"

Input:
str = "Hello World"
insertStr = "Beautiful "
position = 6
Output: Hello Beautiful World

Table of Content

  • Using String Concatenation
  • Using substr_replace() Function

Similar Reads

Insert Characters in a String at a Certain Position using String Concatenation

One way to insert characters into a string is by splitting the string at the desired position, inserting the required string and then concatenating the parts with the new characters....

Insert Characters in a String at a Certain Position using substr_replace() Function

...