If function contains word

You could use regular expressions as it’s better for word matching compared to strpos, as mentioned by other users. A strpos check for are will also return true for strings such as: fare, care, stare, etc. These unintended matches can simply be avoided in regular expression by using word boundaries.

A simple match for are could look something like this:

$a = 'How are you?';

if (preg_match('/bareb/', $a)) {
    echo 'true';
}

On the performance side, strpos is about three times faster. When I did one million compares at once, it took preg_match 1.5 seconds to finish and for strpos it took 0.5 seconds.

Edit:
In order to search any part of the string, not just word by word, I would recommend using a regular expression like

$a = 'How are you?';
$search = 'are y';
if(preg_match("/{$search}/i", $a)) {
    echo 'true';
}

The i at the end of regular expression changes regular expression to be case-insensitive, if you do not want that, you can leave it out.

Now, this can be quite problematic in some cases as the $search string isn’t sanitized in any way, I mean, it might not pass the check in some cases as if $search is a user input they can add some string that might behave like some different regular expression…

Also, here’s a great tool for testing and seeing explanations of various regular expressions Regex101

To combine both sets of functionality into a single multi-purpose function (including with selectable case sensitivity), you could use something like this:

function FindString($needle,$haystack,$i,$word)
{   // $i should be "" or "i" for case insensitive
    if (strtoupper($word)=="W")
    {   // if $word is "W" then word search instead of string in string search.
        if (preg_match("/b{$needle}b/{$i}", $haystack)) 
        {
            return true;
        }
    }
    else
    {
        if(preg_match("/{$needle}/{$i}", $haystack)) 
        {
            return true;
        }
    }
    return false;
    // Put quotes around true and false above to return them as strings instead of as bools/ints.
}

One more thing to take in mind, is that b will not work in different languages other than english.

The explanation for this and the solution is taken from here:

b represents the beginning or end of a word (Word Boundary). This
regex would match apple in an apple pie, but wouldn’t match apple in
pineapple, applecarts or bakeapples.

How about “café”? How can we extract the word “café” in regex?
Actually, bcaféb wouldn’t work. Why? Because “café” contains
non-ASCII character: é. b can’t be simply used with Unicode such as
समुद्र, 감사, месяц and 😉 .

When you want to extract Unicode characters, you should directly
define characters which represent word boundaries.

The answer: (?<=[s,.:;"']|^)UNICODE_WORD(?=[s,.:;"']|$)

So in order to use the answer in PHP, you can use this function:

function contains($str, array $arr) {
    // Works in Hebrew and any other unicode characters
    // Thanks https://medium.com/@shiba1014/regex-word-boundaries-with-unicode-207794f6e7ed
    // Thanks https://www.phpliveregex.com/
    if (preg_match('/(?<=[s,.:;"']|^)' . $word . '(?=[s,.:;"']|$)/', $str)) return true;
}

And if you want to search for array of words, you can use this:

function arrayContainsWord($str, array $arr)
{
    foreach ($arr as $word) {
        // Works in Hebrew and any other unicode characters
        // Thanks https://medium.com/@shiba1014/regex-word-boundaries-with-unicode-207794f6e7ed
        // Thanks https://www.phpliveregex.com/
        if (preg_match('/(?<=[s,.:;"']|^)' . $word . '(?=[s,.:;"']|$)/', $str)) return true;
    }
    return false;
}

As of PHP 8.0.0 you can now use str_contains

<?php
    if (str_contains('abc', '')) {
        echo "Checking the existence of the empty string will always"
        return true;
    }

Home/ Formulas/ Excel IF Function Contains Text – A Partial Match in a Cell

In this post, we will look at how to use the IF function to check if a cell contains specific text.

The IF function when used to compare text values, checks for an exact match. But in this blog post we want to check for a partial match. We are interested if the cell contains the text anywhere within it.

For our example, we have a list of addresses as shown below. And we want to display the word ‘local’ if the address contains the text ‘CB2’.

The sample data of addresses for our IF function contains text examples

So any postcode beginning with ‘CB2’ is considered local. Anything else is not.

Watch the Video – IF Function Contains Text Match

Check If Cell Contains Text

As mentioned, the IF function always performs an exact match. Therefore we need a different function to determine if the text is in the cell or not.

The function we will use is SEARCH. This function will return the position of the text inside the cell, if it is present.

=SEARCH("CB2 ",A2)

You have to be careful when testing for partial matches. And in this example a space is added after CB2 in the string to search for. This is done to prevent it finding matches for postcodes such as CB25 or CB22.

There is also a function called FIND which could be used instead of SEARCH. The key difference between the two is that FIND is case sensitive, and SEARCH is not.

Now this function returns the position of the text if found. We are not interested in this, and simply want to know if it exists.

So we will surround the SEARCH function with ISNUMBER to return TRUE if the text is found, and otherwise return FALSE.

 =ISNUMBER(SEARCH("CB2 ",A2))

We can now finally add the IF function to display the word ‘local’ if ISNUMBER reports TRUE, and the word ‘far’ if FALSE is returned.

=IF(ISNUMBER(SEARCH("CB2 ",A2)),"local","far")

The result of our partial text match

How about Searching for Two Pieces of Text

Lets take it a step further. And what if we consider an address to be local if it contains the text ‘CB2’ or ‘CB3’.

We will bring in the OR function for this. A function that can test multiple conditions and returns TRUE if any one of its tests are met.

The formula below can be used. This time the cell is made blank if it is not local.

=IF(OR(ISNUMBER(SEARCH("CB2 ",A2)),ISNUMBER(SEARCH("CB3 ",A2))),"local","")

The results from searching for two text matches

Reader Interactions

Last Updated — May 20, 2022

Let’s say you have a string and you want to check if it contains a specific word, character or substring. In this article, you will learn about different ways in which you can perform the check using JavaScript. Here are a few variables that we are going to use:

JavaScript

var theString = "I have been looking for Sam.";
var theWord  = "look";
var theCharacter = "I";
var theSubstring = "for Sam";

On This Page

  1. Using String.indexOf() to Check if String Contains Substring
  2. Using String.includes() to Check if String Contains Substring
  3. Using String.search() to Check if String Contains Substring
  4. Using String.match() to Check if String Contains Substring
  5. Quick Summary

Using String.indexOf() to Check if String Contains Substring

The fastest way to check if a string contains a particular word or substring is with the help of String.indexOf() method. This method returns the index of the first occurrence of the specified substring inside the calling String object. If the substring or word is not found, it returns -1.

This means that you can compare the value returned by the indexOf() method to see if it is equal to -1. If the value is not -1, the calling string contains the substring we are looking for.

JavaScript

var theString = "I have been looking for Sam.";
var theWord  = "looking";
var theCharacter = "I";
var theSubstring = "for Sam";


// Output — The word "looking" exists in given string.
if (theString.indexOf(theWord) !== -1) {
  console.log('The word "' + theWord + '" exists in given string.');
}

// Output — The character "I" exists in given string.
if (theString.indexOf(theCharacter) !== -1) {
  console.log('The character "' + theCharacter + '" exists in given string.');
}

// Output — The substring "for Sam" exists in given string.
if (theString.indexOf(theSubstring) !== -1) {
  console.log('The substring "' + theSubstring + '" exists in given string.');
}

You are not limited to the strict inequality operator (!==), you can also use > -1. This is because if the word or substring exists in the given string, the index returned would always be greater than or equal to 0. However, remember that the greater than operator (>) is slower than the strict inequality operator (!==).

One important point that should be kept in mind is that if you meant to search exactly for “look” in the above string, the method would still return an index greater than -1 because “looking” exists in the string. If you are looking for exact matches, you will have to be extra careful.

This method is case-sensitive so you would have got -1 if you searched for “Looking” instead of “looking”.

Using String.includes() to Check if String Contains Substring

You can also use the String.includes() to check if a string contains another word, character or substring. This method will return TRUE if the substring can be found within the main string and FALSE otherwise.

JavaScript

var theString = "I have been looking for Sam.";
var theWord  = "looking";
var theCharacter = "I";
var theSubstring = "for Sam";

// Output — The word "looking" exists in given string.
if (theString.includes(theWord)) {
  console.log('The word "' + theWord + '" exists in given string.');
}

// Output — The character "I" exists in given string.
if (theString.includes(theCharacter)) {
  console.log('The character "' + theCharacter + '" exists in given string.');
}

// Output — The substring "for Sam" exists in given string.
if (theString.includes(theSubstring)) {
  console.log('The substring "' + theSubstring + '" exists in given string.');
}

Just like String.indexOf(), this method is also case-sensitive. One major issue with this method is that the browser support for String.includes() is not as good as String.indexOf(). If you don’t care about the browser support for Internet Explorer, you can use String.includes() without second thought.

Using String.search() to Check if String Contains Substring

String.search() is another method that you can use to check if a string contains another word, substring or character inside the main string. Unlike String.indexOf() and String.include() that we have covered so far, String.search() accepts a regular expression as its parameter. This means that you can also use it to search for complex patterns instead of basic strings.

String.search() returns the index of first match between the regular expression and given string. If no match is found it returns -1. You can compare the return value of String.search() with -1 to see if the given string has the substring you are looking for.

JavaScript

var theString = "I have been looking for Sam.";
var theWord = "looking";
var theCharacter = "I";
var theSubstring = "for Sam";
var theWordExp  = /looking/g;
var theCharacterExp = /I/g;
var theSubstringExp = /for Sam/g;

// Output — The word "looking" exists in given string.
if (theString.search(theWordExp) !== -1) {
  console.log('The word "' + theWord + '" exists in given string.');
}

// Output — The character "I" exists in given string.
if (theString.search(theCharacterExp) !== -1) {
  console.log('The character "' + theCharacter + '" exists in given string.');
}

// Output — The substring "for Sam" exists in given string.
if (theString.search(theSubstringExp) !== -1) {
  console.log('The substring "' + theSubstring + '" exists in given string.');
}

If you are only looking for basic strings, I would suggest that you use either String.includes() or String.indexOf() instead of String.seach().

Using String.match() to Check if String Contains Substring

The String.match() method is used to retrieve all the matches of a regular expression inside the main string. You can use it to check the existence of another word, character or substring inside the main string by passing them as regular expressions. This method will return null if no matches are found.

JavaScript

var theString = "I have been looking for Sam.";
var theWord = "looking";
var theCharacter = "I";
var theSubstring = "for Sam";
var theWordExp  = /looking/g;
var theCharacterExp = /I/g;
var theSubstringExp = /for Sam/g;

// Output — The word "looking" exists in given string.
if (theString.match(theWordExp) !== null) {
  console.log('The word "' + theWord + '" exists in given string.');
}

// Output — The character "I" exists in given string.
if (theString.match(theCharacterExp) !== null) {
  console.log('The character "' + theCharacter + '" exists in given string.');
}

// Output — The substring "for Sam" exists in given string.
if (theString.match(theSubstringExp) !== null) {
  console.log('The substring "' + theSubstring + '" exists in given string.');
}

Actually, you can use String.match() to get a lot more information than just check the existence of a substring. If you include the g flag in the regular expression, it returns the whole array of matched substrings in case of a match. Using it to check if a string has another substring might be overkill. Also, this method is slow compared to other substring checking methods.

Quick Summary

Let’s recap everything that we have covered in this tutorial.

  1. You can use four different methods to check if a string contains another word or substring. These methods are: indexOf(), includes(), search() and match().
  2. The indexOf() method will return the index of the matched string while includes() just returns a Boolean TRUE or FALSE. You can use them both without worrying too much about performance. Both these methods are case-sensitive.
  3. If you are planning to perform case-insensitive searches, using search() with the case-insensitive flag i might be a better idea. However, you will have to escape some special characters for the search to be successful. Using the search() method also gives you more flexibility over simple string matching methods indexOf() and includes().
  4. You can also use match() to see if a string has another word or substring. However, if you just want to know if a match exists, using it might be an overkill.

Let me know if there is anything that you would like me to clarify. Also, you are more than welcome to comment if you know other techniques to check if a string contains another word, character or substring in JavaScript.

Rate this post —

Loading…

Topic: PHP / MySQLPrev|Next

Answer: Use the PHP strpos() Function

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.

Let’s check out an example to understand how this function basically works:

<?php
$word = "fox";
$mystring = "The quick brown fox jumps over the lazy dog";
 
// Test if string contains the word 
if(strpos($mystring, $word) !== false){
    echo "Word Found!";
} else{
    echo "Word Not Found!";
}
?>


Related FAQ

Here are some more FAQ related to this topic:

  • How to count how many times a substring occurs in a string in PHP
  • How to replace a word inside a string in PHP
  • How to split a string into an array in PHP

  • #2

Something like

Code:

=if(iserror(search("Balance",a1,1)),"No","Yes")

  • #3

Thanks a million! How do you figure that kind of stuff out without asking someone? I googled for thirty minutes??

  • #4

You’re welcome — thanks for coming back to say thanks.

To be honest, this is not really advanced stuff, you just pick it up. If you keep an interest in this board, you’ll pick up alot of stuff like that.

  • #6

Ok, a follow up then…since i do not fully under the iserror formula you referenced what if I want it to = column A (old Acct) if it does not contain «Balance»?

IF(ISERROR(SEARCH(«Balance»,A2,1)),»No»,»Total_Inventory»)

<TABLE style=»WIDTH: 314pt; BORDER-COLLAPSE: collapse» cellSpacing=0 cellPadding=0 width=418 border=0 x:str><COLGROUP><COL style=»WIDTH: 157pt; mso-width-source: userset; mso-width-alt: 7643″ span=2 width=209><TBODY><TR style=»HEIGHT: 12.75pt» height=17><TD class=xl72 style=»BORDER-RIGHT: windowtext 0.5pt solid; BORDER-TOP: #d4d0c8; BORDER-LEFT: #d4d0c8; WIDTH: 157pt; BORDER-BOTTOM: windowtext 0.5pt solid; HEIGHT: 12.75pt; BACKGROUND-COLOR: #ffffc0″ width=209 height=17>Old Acct</TD><TD class=xl72 id=td_post_1716813 style=»BORDER-RIGHT: windowtext 0.5pt solid; BORDER-TOP: #d4d0c8; BORDER-LEFT: #d4d0c8; WIDTH: 157pt; BORDER-BOTTOM: windowtext 0.5pt solid; BACKGROUND-COLOR: #ffffc0″ width=209>New Account</TD></TR><TR style=»HEIGHT: 15pt» height=20><TD class=xl73 style=»BORDER-RIGHT: windowtext 0.5pt solid; BORDER-TOP: windowtext; BORDER-LEFT: #d4d0c8; BORDER-BOTTOM: windowtext 0.5pt solid; HEIGHT: 15pt; BACKGROUND-COLOR: #ffffc0″ height=20>Allocations_Balance</TD><TD class=xl74 style=»BORDER-RIGHT: #d4d0c8; BORDER-TOP: #d4d0c8; BORDER-LEFT: #d4d0c8; BORDER-BOTTOM: #d4d0c8; BACKGROUND-COLOR: transparent» x:fmla=’=IF(ISERROR(SEARCH(«Balance»,A2,1)),»No»,»Total_Inventory»)’>Total_Inventory</TD></TR><TR style=»HEIGHT: 15pt» height=20><TD class=xl73 style=»BORDER-RIGHT: windowtext 0.5pt solid; BORDER-TOP: windowtext; BORDER-LEFT: #d4d0c8; BORDER-BOTTOM: windowtext 0.5pt solid; HEIGHT: 15pt; BACKGROUND-COLOR: #ffffc0″ height=20>Allocations_Balance</TD><TD class=xl74 style=»BORDER-RIGHT: #d4d0c8; BORDER-TOP: #d4d0c8; BORDER-LEFT: #d4d0c8; BORDER-BOTTOM: #d4d0c8; BACKGROUND-COLOR: transparent» x:fmla=’=IF(ISERROR(SEARCH(«Balance»,A3,1)),»No»,»Total_Inventory»)’>Total_Inventory</TD></TR><TR style=»HEIGHT: 15pt» height=20><TD class=xl73 style=»BORDER-RIGHT: windowtext 0.5pt solid; BORDER-TOP: windowtext; BORDER-LEFT: #d4d0c8; BORDER-BOTTOM: windowtext 0.5pt solid; HEIGHT: 15pt; BACKGROUND-COLOR: #ffffc0″ height=20>Allocations_Activity</TD><TD class=xl74 style=»BORDER-RIGHT: #d4d0c8; BORDER-TOP: #d4d0c8; BORDER-LEFT: #d4d0c8; BORDER-BOTTOM: #d4d0c8; BACKGROUND-COLOR: transparent» x:fmla=’=IF(ISERROR(SEARCH(«Balance»,A4,1)),»No»,»Total_Inventory»)’>No</TD></TR><TR style=»HEIGHT: 15pt» height=20><TD class=xl73 style=»BORDER-RIGHT: windowtext 0.5pt solid; BORDER-TOP: windowtext; BORDER-LEFT: #d4d0c8; BORDER-BOTTOM: windowtext 0.5pt solid; HEIGHT: 15pt; BACKGROUND-COLOR: #ffffc0″ height=20>Allocations_Balance</TD><TD class=xl74 style=»BORDER-RIGHT: #d4d0c8; BORDER-TOP: #d4d0c8; BORDER-LEFT: #d4d0c8; BORDER-BOTTOM: #d4d0c8; BACKGROUND-COLOR: transparent» x:fmla=’=IF(ISERROR(SEARCH(«Balance»,A5,1)),»No»,»Total_Inventory»)’>Total_Inventory</TD></TR><TR style=»HEIGHT: 15pt» height=20><TD class=xl73 style=»BORDER-RIGHT: windowtext 0.5pt solid; BORDER-TOP: windowtext; BORDER-LEFT: #d4d0c8; BORDER-BOTTOM: windowtext 0.5pt solid; HEIGHT: 15pt; BACKGROUND-COLOR: #ffffc0″ height=20>Allocations_Activity</TD><TD class=xl74 style=»BORDER-RIGHT: #d4d0c8; BORDER-TOP: #d4d0c8; BORDER-LEFT: #d4d0c8; BORDER-BOTTOM: #d4d0c8; BACKGROUND-COLOR: transparent» x:fmla=’=IF(ISERROR(SEARCH(«Balance»,A6,1)),»No»,»Total_Inventory»)’>No</TD></TR><TR style=»HEIGHT: 15pt» height=20><TD class=xl73 style=»BORDER-RIGHT: windowtext 0.5pt solid; BORDER-TOP: windowtext; BORDER-LEFT: #d4d0c8; BORDER-BOTTOM: windowtext 0.5pt solid; HEIGHT: 15pt; BACKGROUND-COLOR: #ffffc0″ height=20>Allocations_Activity</TD><TD class=xl74 style=»BORDER-RIGHT: #d4d0c8; BORDER-TOP: #d4d0c8; BORDER-LEFT: #d4d0c8; BORDER-BOTTOM: #d4d0c8; BACKGROUND-COLOR: transparent» x:fmla=’=IF(ISERROR(SEARCH(«Balance»,A7,1)),»No»,»Total_Inventory»)’>No</TD></TR><TR style=»HEIGHT: 15pt» height=20><TD class=xl73 style=»BORDER-RIGHT: windowtext 0.5pt solid; BORDER-TOP: windowtext; BORDER-LEFT: #d4d0c8; BORDER-BOTTOM: windowtext 0.5pt solid; HEIGHT: 15pt; BACKGROUND-COLOR: #ffffc0″ height=20>Allocations_Activity</TD><TD class=xl74 style=»BORDER-RIGHT: #d4d0c8; BORDER-TOP: #d4d0c8; BORDER-LEFT: #d4d0c8; BORDER-BOTTOM: #d4d0c8; BACKGROUND-COLOR: transparent» x:fmla=’=IF(ISERROR(SEARCH(«Balance»,A8,1)),»No»,»Total_Inventory»)’>No</TD></TR></TBODY></TABLE>

  • #8

«IF(ISERROR(SEARCH(«Balance»,A2,1)),»No»,»Total_Inventory»)»

Just a small warning — iserror() checks for all errors, including syntactical ones in the formula’s construction. with a search(), you’re better of with isnumber(), cos:

=if(iserror(sm(a1:a10),»No sales — fire everyone»,sum(a1:a10))

…is not the sort of error you want to mask. in general, always try to check for the condition at issue, not a general error.

Понравилась статья? Поделить с друзьями:
  • If found in list excel
  • If and search functions in excel
  • If formulas in word tables
  • If and or syntax in excel
  • If formula with color in excel