Home > Article > Backend Development > PHP string exercise 4: Determine whether a string contains a specific word
In "PHP String Exercise 3: 4 Methods for Converting String Sizes", we introduced four common methods for converting the case of strings. In this article, we will continue with strings. The series determines whether a string contains a specific string.
In fact, there is a very simple way to achieve such a judgment. Let’s look at the code directly:
As follows:
<?php $str1 = 'The quick brown fox jumps over the lazy dog.'; if (strpos($str1,'jumps') !== false) { echo '特定词出现了'; } else { echo '特定词未出现'; }
In this code, we create a String variable $str1, then we randomly specify the word "jumps" and check to see if this word exists in $str1 through the if...else statement;
Let's take a look at the judgment results first:
As shown in the picture, the result is that "a specific word appears". From the above code, it is indeed true.
So here we mainly use a function strpos and the operator "!==".
The built-in function strpos() in PHP is used to find the first occurrence of a string in another string. Its syntax is "strpos(string,find,start)
", where the parameter string specifies the string to be searched, find specifies the string to find, and start is optional and specifies where to start the search; this function returns the position of the first occurrence of the string in another string , returns FALSE if the string is not found.
It should be noted that the strpos() function is case-sensitive.
!==
means "absolutely not equal" in comparison operators, !==
means "not equal" in array operators .
Finally, I recommend reading "php detects whether a string contains a string". This article introduces other methods of detecting inclusion. Friends who are interested can learn about it~
Recommend the classic course "PHP String Processing (Jade Girl Heart Sutra Edition)", it's free~ come and learn!
The above is the detailed content of PHP string exercise 4: Determine whether a string contains a specific word. For more information, please follow other related articles on the PHP Chinese website!