w3resource

PHP Exercises: Create a new string taking 3 characters from the middle of a given string at least 3

PHP Basic Algorithm: Exercise-74 with Solution

Write a PHP program to create a new string taking 3 characters from the middle of a given string at least 3.

Sample Solution:

PHP Code :

<?php
// Define a function named 'test' that extracts a substring of length 3 from the middle of the input string
// If the length of the string is odd, the middle is calculated as (length - 1) / 2 - 1
// If the length is even, the middle is calculated as length / 2 - 1
function test($s1)
{ 
   // Use substr to extract a substring of length 3 from the middle of the string
   // If the length is odd, calculate the middle as (length - 1) / 2 - 1
   // If the length is even, calculate the middle as length / 2 - 1
   return substr($s1, (strlen($s1) - 1) / 2 - 1, 3);
}

// Test the 'test' function with different strings, then display the results using echo
echo test("Hello")."\n";
echo test("Python")."\n";
echo test("abc")."\n";
?>

Sample Output:

ell
yth
abc

Flowchart:

Flowchart: Create a new string taking 3 characters from the middle of a given string at least 3.

PHP Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a PHP program to create a new string of length 2 starting at the given index of a given string.
Next: Write a PHP program to create a new string of length 2, using first two characters of a given string. If the given string length is less than 2 use '#' as missing characters.

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.