Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a string does not contain a specific phrase?

Tags:

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.

like image 746
Dead Girl Avatar asked Jan 10 '14 17:01

Dead Girl


People also ask

How do I check if a string not contains a specific word?

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.

How do you check if a string does not contain a word in Python?

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 .

How do you check if a string does not contain a character in C++?

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.

How do I check if a string contains a specific number?

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.


1 Answers

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.

like image 95
Rottingham Avatar answered Sep 23 '22 18:09

Rottingham