w3resource

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

PHP String: Exercise-17 with Solution

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

PHP Code Editor:

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

Previous: Write a PHP script to get a hex dump of a string.
Next: Write a PHP script to get the first word of a sentence.

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.