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.
Example: PHP if string contains
Let’s see an example to understand that how this function basically works:
|
1 2 3 4 5 6 7 8 9 10 11 |
<?php $word = "chocolates"; $mystring = "Life is like a box of chocolates, you never know what you're gonna get"; // Test if string contains the word if(strpos($mystring, $word) !== false){ echo "Word Found!"; } else{ echo "Word Not 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”.
|
1 2 3 4 5 6 7 |
<?php $mystr = 'This is powerful politician man'; if (strpos($mystr, 'This') !== false) { echo '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.
|
1 2 3 4 5 6 7 8 9 |
<?php $mystr = 'This is powerful politician man'; $substr = "Welcome"; if (strpos($mystr, $substr) !== false) { echo 'True'; } ?> |
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.
|
1 2 3 4 5 6 7 |
<?php $mystr = 'This is powerful politician man'; if (strpos($mystr, 'This') === 0 ) { echo '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.