Open In App

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

Last Updated : 27 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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 GeeksforGeeks"
insertStr = "to "
position = 8
Output: "Welcome to GeeksforGeeks"

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

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)

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

PHP provides the substr_replace() function, which is used for replacing a part of a string with another string, and can also be used for insertion. The substr_replace() function takes 4 arguments: the original string, the string to be inserted, the position for insertion, and the length of the substring to be replaced (0 in this case, as we are only inserting), and return the updated string.

Example: Implementation of inserting characters in a string at a certain position using substr_replace() function.

PHP




<?php
  
// Given Data
$str = "Hello World";
$insertStr = "Beautiful ";
$position = 6;
  
// Using substr_replace() for string insertion
$newStr = substr_replace($str, $insertStr, $position, 0);
echo $newStr;
  
?>


Output

Hello Beautiful World

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



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads