w3resource

PHP Exercises: Create a new string using the two middle characters of a given string of even length


70. Middle Two Characters from Even-Length String

Write a PHP program to create a new string using the two middle characters of a given string of even length (at least 2).

Sample Solution:

PHP Code :

<?php
// Define a function named 'test' that extracts a substring of two characters from the middle of the input string
function test($s1)
{ 
    // Calculate the starting index to obtain the middle two characters
    return substr($s1, strlen($s1)/2 - 1, 2); 
}

// Test the 'test' function with different strings and display the results
echo test("Hell")."\n";
echo test("JS")."\n";
echo test("  ")."\n";
?>

Explanation:

  • Function Definition:
    • A function named test is defined, which takes one parameter, $s1, representing the input string.
  • Calculating the Starting Index:
    • The function uses the strlen($s1)/2 - 1 expression to calculate the starting index for extracting a substring.
    • This calculation determines the middle of the string:
      • strlen($s1)/2 finds the midpoint.
      • Subtracting 1 adjusts the index to start from one character before the midpoint.
  • Extracting the Substring:
    • The function then calls substr($s1, strlen($s1)/2 - 1, 2):
      • This extracts a substring starting at the calculated index and retrieves 2 characters from that point.

Output:

el
JS

Flowchart:

Flowchart: Create a new string using the two middle characters of a given string of even length.

For more Practice: Solve these Related Problems:

  • Write a PHP script to extract a new string consisting of the two middle characters of an even-length input.
  • Write a PHP function to calculate the midpoint of a string and return the two central characters.
  • Write a PHP program to check that a string’s length is even and then slice out the middle two characters.
  • Write a PHP script to determine the indices for the middle characters and form a new two-character string from them.

Go to:


PREV : Remove First and Last Character (Any Length).
NEXT : Check if String Ends with "on".

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.