w3resource

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

PHP Basic Algorithm: Exercise-70 with Solution

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.

PHP Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a PHP program to create a new string without the first and last character of a given string of any length.
Next: Write a PHP program to check if a given string ends with "on".

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/php-exercises/basic-algorithm/php-basic-algorithm-exercise-70.php