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

Explanation:

  • Function Definition:
    • A function named test is defined with a single parameter:
      • $s1: the input string.
  • Substring Extraction:
    • The function calculates the starting index for extracting a 3-character substring from the middle of the input string:
      • If the string length is odd, (strlen($s1) - 1) / 2 - 1 gives the starting position of the middle three characters.
      • If the string length is even, the same formula approximates the middle.
    • substr($s1, (strlen($s1) - 1) / 2 - 1, 3) extracts three characters starting from the calculated middle index.

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.



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-74.php