PHP String Exercises: Check whether a string contains a specific string
Write a PHP script to check whether a string contains a specific string?
Sample string : 'The quick brown fox jumps over the lazy dog.'
Check whether the said string contains the string 'jumps'.
Visual Presentation:
Sample Solution:
PHP Code:
<?php
// Define the input string
$str1 = 'The quick brown fox jumps over the lazy dog.';
// Check if the word "jumps" is present in the string
if (strpos($str1,'jumps') !== false)
{
// If present, echo a message indicating its presence
echo 'The specific word is present.';
}
else
{
// If not present, echo a message indicating its absence
echo 'The specific word is not present.';
}
?>
Output:
The specific word is present.
Explanation:
The above PHP code checks if the word "jumps" is present in the given string. It uses the "strpos()" function to find the position of the substring "jumps" within the string '$str1'. If the word "jumps" is found (i.e., if "strpos()" returns a value not equal to 'false'), it prints a message indicating that the word is found. Otherwise, it prints a message indicating that the word is not present.
Flowchart :
PHP Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a PHP script to split the specific string.
Next: Write a PHP script to convert the value of a PHP variable to string.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics