w3resource

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


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";
?>

Explanation:

  • Function Definition:
    • The function test is defined with one parameter:
      • $s1: the input string to check.
  • Prefix Check (First Condition):
    • The function checks if the first three characters of $s1 are "abc":
      • if (substr($s1, 0, 3) == "abc")
    • If true:
      • It returns the string "abc".
  • Prefix Check (Second Condition):
    • If the first condition is false, it checks if the first three characters of $s1 are "xyz":
      • else if (substr($s1, 0, 3) == "xyz")
    • If true:
      • It returns the string "xyz".
  • Default Return Value:
    • If neither condition is met:
      • It returns an empty string "".

    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.