w3resource

PHP Exercises: Check if a given string begins with 'abc' or 'xyz'

PHP Basic Algorithm: Exercise-79 with Solution

Write a PHP program to check if a given string begins with 'abc' or 'xyz'. If the string begins with 'abc' or 'xyz' return 'abc' or 'xyz' otherwise return the empty string.

Sample Solution:

PHP Code :

<?php
// Define a function named 'test' that checks the prefix of a string
function test($s1)
{ 
    // Check if the first three characters of $s1 are "abc"
    if (substr($s1, 0, 3) == "abc")
    {
        // If true, return "abc"
        return "abc";
    }
    // Check if the first three characters of $s1 are "xyz"
    else if (substr($s1, 0, 3) == "xyz")
    {
        // If true, return "xyz"
        return "xyz";
    }
    // If the conditions are not met, return an empty string
    else
    {
        return "";
    }
}

// Test the 'test' function with different strings, then display the results using echo
echo test("abc")."\n";
echo test("abcdef")."\n";
echo test("C")."\n";
echo test("xyz")."\n";
echo test("xyzsder")."\n";
?>

Sample Output:

abc
abc

xyz
xyz

Flowchart:

Flowchart: Check if a given string begins with 'abc' or 'xyz'.

PHP Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a PHP program to create a new string from a given string after swapping last two characters.
Next: Write a PHP program to check whether the first two characters and last two characters of a given string are same.

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.