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";
?>
Explanation:
- The function test is defined with one parameter:
- $s1: the input string to check.
- 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".
- 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".
- If neither condition is met:
- It returns an empty string "".
Output:
abc abc xyz xyz
Flowchart:
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.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/php-exercises/basic-algorithm/php-basic-algorithm-exercise-79.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics