w3resource

PHP Exercises: Create a new string without the first and last character of a given string of length atleast two


64. Remove First and Last Character

Write a PHP program to create a new string without the first and last character of a given string of length atleast two.

Sample Solution:

PHP Code :

<?php
// Define a function named 'test' that manipulates the substring of s1
function test($s1)
{
    // Use substr to exclude the first character, then another substr to exclude the last two characters
    return substr(substr($s1, 1, strlen($s1) - 1), 0, strlen($s1) - 2);
}

// Test the 'test' function with different input strings and display the results
echo test("Hello")."\n";
echo test("Hi")."\n";
echo test("Python")."\n";
?>

Explanation:

  • Function Definition:
    • The function test takes one parameter, $s1, which is a string.
  • Manipulate Substring:
    • The function uses substr twice to exclude certain characters:
      • substr($s1, 1, strlen($s1) - 1): Removes the first character from $s1.
      • Another substr call then extracts a substring from the resulting string, stopping before the last two characters.
  • Return:
    • The function returns the modified substring, excluding the first and last two characters of the original $s1.

Output:

ell

ytho

Flowchart:

Flowchart: Create a new string without the first and last character of a given string of length atleast two.

For more Practice: Solve these Related Problems:

  • Write a PHP script to return a new string that excludes the first and last characters of the input, assuming a minimum length of two.
  • Write a PHP function to trim the first and last letters from a string and output the resulting substring.
  • Write a PHP program to remove the boundary characters of a string and handle errors if the string is too short.
  • Write a PHP script to slice a string from index 1 to length-2 and return the inner substring.

Go to:


PREV : First Half of Even-Length String.
NEXT : Concat Shorter into Longer.

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.