w3resource
php Programming Exercies

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'.

Pictorial 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';
$string_to_insert ='quick';
$insert_pos = 4;
$new_string = substr_replace($original_string, $string_to_insert.' ', $insert_pos, 0);
echo $new_string."\n";
?>

Sample Output:

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?



New Content: Composer: Dependency manager for PHP, R Programming