Open In App

Insert string at specified position in PHP

Last Updated : 17 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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 from zero. See the examples below.

Input : sentence = ‘I am happy today.’

string = ‘very’

position = 4

Output :I am very happy today.

Input : sentence = ‘I am happy today.’

string = ‘ very’

position = 4

Output : I am very happy today.

Below are the methods to Insert string at specified position in PHP:

Using substr_replace()

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.

Example:

PHP
<?php
$sentence = 'I am happy today.';
$string = 'very ';
$position = '5';

echo substr_replace( $sentence, $string, $position, 0 );
?>

Output
I am very happy today.

Using string concatenation and substr()

You can achieve inserting a string at a specified position in PHP by using string concatenation and the substr() function.

Example:

PHP
<?php
function insertString($sentence, $string, $position) {
    // Ensure position is within bounds of the sentence
    if ($position < 0 || $position > strlen($sentence)) {
        return "Invalid position";
    }
    
    // Insert the string at the specified position
    $newSentence = substr($sentence, 0, $position) 
      	. $string . substr($sentence, $position);
    
    return $newSentence;
}


$sentence = 'I am happy today.';
$string = 'very';
$position = 4;
$newSentence = insertString($sentence, $string, $position);
echo $newSentence; // Output: I amvery happy today.

?>

Output
I amvery happy today.

Using str_split() and Concatenation

The str_split() function can be used to split the string into an array of substrings. By specifying the length parameter, you can split the string into two parts at the desired position and then insert the new string between these parts.

Example:

PHP
<?php
// Function to insert a string at a specified position
function insertStringAtPosition($sentence, $stringToInsert, $position) {
    // Split the sentence into two parts at the specified position
    $part1 = substr($sentence, 0, $position);
    $part2 = substr($sentence, $position);

    // Concatenate the parts with the string to be inserted
    $newSentence = $part1 . $stringToInsert . $part2;

    return $newSentence;
}


$sentence1 = 'I am happy today.';
$string1 = 'very ';
$position1 = 5;

$sentence2 = 'I am happy today.';
$string2 = ' very';
$position2 = 4;

echo insertStringAtPosition($sentence1, $string1, $position1) . "\n"; 
echo insertStringAtPosition($sentence2, $string2, $position2) . "\n"; 
?>

Output
I am very happy today.
I am very happy today.



Next Article

Similar Reads