w3resource

PHP String Exercises: Insert a string at the specified position in a given string


17. Insert a String at a Specified Position

Write a PHP script to insert a string at the specified position in a given string.

Original String : 'The brown fox'
Insert 'quick' between 'The' and 'brown'.

Visual Presentation:

PHP String Exercises: Insert a string at the specified position in a given string

Sample Solution:

PHP Code:

<?php
$original_string = 'The brown fox'; 
// Define the original string.
$string_to_insert ='quick'; 
// Define the string to be inserted.
$insert_pos = 4; 
// Define the position where the insertion will occur.
$new_string = substr_replace($original_string, $string_to_insert.' ', $insert_pos, 0); 
// Insert the substring at the specified position in the original string.
echo $new_string."\n"; 
// Output the modified string.
?>

Output:

The quick brown fox

Explanation:

The above PHP code snippet inserts the string ''quick'' into the original string ''The brown fox'' at position 4 (zero-based indexing). It uses the 'substr_replace()' function, which replaces a portion of a string with another string. The inserted string is followed by a space to ensure proper spacing. Finally, it outputs the modified string ''The quick brown fox''.

Flowchart :

Flowchart: Insert a string at the specified position in a given string

For more Practice: Solve these Related Problems:

  • Write a PHP script to insert a given substring at a specified position in another string using substr_replace().
  • Write a PHP function that accepts an original string, an insertion string, and an index, then returns the modified string.
  • Write a PHP program to insert a word into the middle of a sentence and output the resulting string.
  • Write a PHP script to dynamically determine the middle of a string and insert a user-specified substring at that position.

Go to:


PREV : Get Hex Dump of a String.
NEXT : Get First Word of a Sentence.

PHP Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.