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";
?>

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



Follow us on Facebook and Twitter for latest update.