w3resource

PHP Exercises: 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

PHP Basic Algorithm: Exercise-85 with Solution

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.

Sample Solution:

PHP Code :

<?php
// Define a function named 'test' that manipulates a string based on the presence of the character 'a'
function test($s1)
{ 
    // Check if the length of $s1 is 1 and if the character is 'a'
    if (strlen($s1) == 1 && substr($s1, 0, 1) == "a")
    {
        // Remove the character 'a' from $s1
        $s1 = substr($s1, 1);
    }

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

        // Check if the first character is 'a'
        if (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("aacda") . "\n";
echo test("jython") . "\n";
?>

Sample Output:

bcab
Python
cda
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 without the first and last character if the first or last characters are 'a' otherwise return the original given string.
Next: Write a PHP program to check a given array of integers of length 1 or more and return true if 10 appears as either first or last element in the given array.

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.