w3resource

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

PHP Basic Algorithm: Exercise-69 with Solution

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

Sample Solution:

PHP Code :

<?php
// Define a function named 'test' that extracts the middle portion of a string, excluding the first and last characters
function test($s1)
{ 
    // Check if the string has less than 2 characters and return an empty string if true
    return strlen($s1) < 2 ? "" : substr($s1, 1, strlen($s1) - 2);
}

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

Sample Output:

ell

Flowchart:

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

PHP Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a PHP program to move the last two characters to the start of a given string of length at least two.
Next: Write a PHP program to create a new string using the two middle characters of a given string of even length (at least 2).

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.