How to invert the function of How do I check if a string contains a specific word in PHP?
if (strpos($a,'are') !== false) { echo 'true'; }
So it echoes true
if are
is not found in $a
.
You can use the PHP strpos() function to check whether a string contains a specific word or not. The strpos() function returns the position of the first occurrence of a substring in a string. If the substring is not found it returns false . Also note that string positions start at 0, and not 1.
Using Python's "in" operator The simplest and fastest way to check whether a string contains a substring or not in Python is the "in" operator . This operator returns true if the string contains the characters, otherwise, it returns false .
We can use the string::find function to search for a specific character in a string. It returns the index of the first instance of the character or string::npos if the character is not present.
To find whether a given string contains a number, convert it to a character array and find whether each character in the array is a digit using the isDigit() method of the Character class.
The code here:
if (strpos($a, 'are') !== false) { // The word WAS found }
Means that the word WAS found in the string. If you remove the NOT (!) operator, you have reversed the condition.
if (strpos($a, 'are') === false) { // The word was NOT found }
the === is very important, because strpos will return 0 if the word 'are' is at the very beginning of the string, and since 0 loosely equals FALSE, you would be frustrated trying to find out what was wrong. The === operator makes it check very literally if the result was a boolean false and not a 0.
As an example,
if (!strpos($a, 'are')) { // String Not Found }
This code will say the string 'are' is not found, if $a = "are you coming over tonight?", because the position of 'are' is 0, the beginning of the string. This is why using the === false check is so important.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With