w3resource

PHP Exercises: Insert a given string into middle of the another given string of length 4


60. Insert String into Middle

Write a PHP program to insert a given string into middle of the another given string of length 4.

Sample Solution:

PHP Code :

<?php
// Define a function named 'test' that inserts a word into a string at a specific position
function test($s1, $word)
{
    // Use substr to concatenate the first two characters of s1, followed by the 'word', and then the rest of s1
    return substr($s1, 0, 2) . $word . substr($s1, 2);
}

// Test the 'test' function with different input strings and display the results
echo test("[[]]", "Hello")."\n";
echo test("(())", "Hi");
?>

Explanation:

  • Function Purpose:
    • The test function takes two parameters, $s1 (a string) and $word (a string to insert), and inserts $word into $s1 at the third position (after the first two characters).
  • Insertion Logic:
    • The function uses substr to split $s1 into two parts:
      • The first two characters of $s1 (substr($s1, 0, 2)).
      • The rest of $s1 from the third character onward (substr($s1, 2)).
    • It then concatenates the parts: the first two characters of $s1, followed by $word, followed by the rest of $s1.

Output:

[[Hello]]
((Hi))

Flowchart:

Flowchart: Insert a given string into middle of the another given string of length 4.

For more Practice: Solve these Related Problems:

  • Write a PHP script to insert a given string into the center of another string that has a fixed length of 4 characters.
  • Write a PHP function to splice one string into the middle of a four-character string and output the result.
  • Write a PHP program to combine two strings by embedding the longer string into the exact middle of a four-character pattern.
  • Write a PHP script to calculate the midpoint of a fixed-length string and insert an input substring at that position.

Go to:


PREV : String Pattern: s1s2s2s.
NEXT : Three Copies of Last Two Characters.

PHP Code Editor:



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.