PHP if string contains | How do I check if a string contains a specific word?

Summary: In this article, we learn, How do I check if a string contains a specific word in PHP?

Answer: Use the PHP strpos() Function

A String is a sequence of characters, it is used either as a literal constant or as a few kinds of variables. A specific or particular part of a string is called a substring.
The PHP provides strpos( ) function which is used to check if a string contains a specific substring or not. This function returns the position of the 1st (first) occurrence of a substring in a string. If substring not found, then it returns false as output.

.
Note: The string positions start at 0, and not 1.

Example: PHP if string contains

Let’s see an example to understand that how this function basically works:

Output: Word Found!

Let’s see another three examples, How to check if a string contains a substring or not. furthermore, you can check if the substring is at the start or beginning of the main string.

Example 1. To Check PHP if string contains

The given below following code segment will evaluate to true because the main string $mystr contains the substring ‘This‘ in it. This will print “True”.

Output: True

Example 2.

The given below following code segment will evaluate to false because the main string $mystr doesn’t contains the substring ‘Welcome‘ in it. This will nothing print.

Output: None

Example 3.

The code segment will check if a String contains a substring at start or begnning. The following code will evaluate to true because the main string $mystr contains the substring ‘This‘ at start.

Output: True

Conclusion

In this tutorial, you have learned How do I check if a string contains a specific word in PHP? or to check if a string contains a substring using PHP strpos( ) function. Because of strpos() will find the position of the first occurrence of a substring/word in a string. The position will start at index 0 and if the word does not exist then it will return FALSE.