w3resource

PHP String Exercises: Check whether a string contains a specific string


3. Check if String Contains Another

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:

PHP String Exercises: Check whether a string contains a specific string

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 :

Flowchart: Check whether a string contains a specific string

For more Practice: Solve these Related Problems:

  • Write a PHP function that searches for a specific substring within a larger string using strpos() and returns its position if found.
  • Write a PHP script to determine whether a sentence contains a particular word, ignoring case differences.
  • Write a PHP program that checks if multiple target substrings exist within a string and returns an associative array of results.
  • Write a PHP script to highlight all occurrences of a specified substring within a string by wrapping them in HTML tags.

Go to:


PREV : Split String Into Time Format.
Next: Convert Variable to String.

PHP Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

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.