w3resource

PHP Exercises: Create a new string from a given string without the first and last character if the first or last characters are 'a' otherwise return the original given string

PHP Basic Algorithm: Exercise-84 with Solution

Write a PHP program to create a new string from a given string without the first and last character if the first or last characters are 'a' otherwise return the original given string.

Sample Solution:

PHP Code :

<?php
// Define a function named 'test' that removes the character 'a' from the beginning and end of a string
function test($s1)
{ 
    // Check if the length of $s1 is greater than 0 and if the last character is 'a'
    if (strlen($s1) > 0 && substr($s1, strlen($s1)-1, 1) == "a")
    {
        // Remove the last character from $s1
        $s1 = substr($s1, 0, strlen($s1) - 1);
    }

    // Check if the length of $s1 is greater than 0 and if the first character is 'a'
    if (strlen($s1) > 0 && substr($s1, 0, 1) == "a")
    {
        // Remove the first character from $s1
        $s1 = substr($s1, 1);
    }

    // Return the modified or original string
    return $s1;
}

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

Sample Output:

bcab
Python
bcd
jython

Flowchart:

Flowchart: Create a new string from a given string without the first and last character if the first or last characters are 'a' otherwise return the original given string.

PHP Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a PHP program to create a new string from a given string. If the two characters of the given string from its beginning and end are same return the given string without the first two characters otherwise return the original string.
Next: Write a PHP program to create a new string from a given string. If the first or first two characters is 'a', return the string without those 'a' characters otherwise return the original given string.

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.