If text 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 » Check If A String Contains A Specific Word In PHP

Last updated on December 24, 2020 by

Often, developers want to check string contains a specific word or not in PHP. For that, we can use strpos() and preg_match() functions to do that. Let’s see how to do it.

Check If a String Contains a Specific Word

01 Find Exact Match Using the PHP preg_match() Function

You can use the PHP preg_match() function to check whether a text contains a specific word or not.

Use: The preg_match() function is used to find the exact match of a pattern in a string of text using a regular expression search.

Return: This function will return true if the pattern is matched otherwise it will return false.

Example:

The following example will check for the exact match of the word like we are searching for aware then it will only search for the aware word and not a partial word like "beware", "unaware", "awareness", etc.

<?php 

/* The b in the pattern indicates a word boundary, so only the distinct */

$string = "Oh! I am also not aware of this ";

if (preg_match("/awareb/", $string)) :
    echo "A match was found.";
else:
    echo "A match was not found.";
endif;

The b expression in the pattern specify a word boundary.

Case Insensitive Search with preg_match()

For case-insensitive search put the "i" after the pattern delimiter as shown below:

<?php

$string = "Oh! I am also not AWARE of this ";

// The "i" after the pattern delimiter indicates a case-insensitive search

if (preg_match("/aware/i", $string)) :
    echo "A match was found.";
else:
    echo "A match was not found.";
endif;

In the above example, we are checking for aware specific word but our string contains a capital AWARE but although it will return A match was found. due to case-insensitive searches.

02 Use the PHP strpos() Function

You can also use the PHP’s strpos() function to check whether a string contains a specific word or not.

The strpos() function will return the position of the first occurrence of a substring in a string. It will return false if the match not found.

Please note that strpos() start searching from 0 index so use strict comparision operator using === or !== otherwise it will considered 0 = false.

Let’s see the example for better understanding:

<?php

$string = "I am not aware of this";

if ( strpos( $string, 'aware' ) !== false ) :
	echo 'true';
else:
	echo 'false';
endif;

You can also check if the string contains a word or not by using other PHP functions like stripos(), strstr(), stristr(), substr_count(), mb_strpos(), etc.

Why to Use preg_match() And Not strpos()

The preg_match() is better for word matching in comparison to strpos() because if you are checking the string contains a word like "are" and if your string contains words like careful, beware, prepare, etc. then strpos() will also return true.

To understand this situation please considered the below example:

<?php

$string = "I am not aware of this";

if ( strpos( $string, 'are' ) !== false ) :
	echo 'true';
else:
	echo 'false';
endif;

The above example should return the false, but it’s returning true as output.

Output:

true

That’s it for now. We hope this article helped you to check if a string contains a specific word in PHP.

Additionally, read our guide:

  1. Best Way to Remove Public from URL in Laravel
  2. Error After php artisan config:cache In Laravel
  3. Specified Key Was Too Long Error In Laravel
  4. Active Directory Using LDAP in PHP or Laravel
  5. How To Use The Laravel Soft Delete
  6. How To Add Laravel Next Prev Pagination
  7. cURL error 60: SSL certificate problem: unable to get local issuer certificate
  8. Difference Between Factory And Seeders In Laravel
  9. Laravel: Increase Quantity If Product Already Exists In Cart
  10. How To Calculate Age From Birthdate
  11. How To Find Duplicate Records in Database

Please let us know in the comments if everything worked as expected, your issues, or any questions. If you think this article saved your time & money, please do comment, share, like & subscribe. Thank you in advance 🙂. Keep Smiling! Happy Coding!

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
  • Remove From My Forums
  • Question

  • Hello Everybody,

    I have string s= «Hello1 Hello2»;

    s.contains(«Hello»); will return me true. but i want to see if the string contains the exact word «Hello» which it does not.

    how can i do that?

    Thanks,
    Jan :)

Answers

  • U can use a regular expression like so:

    
    
    bool contains = Regex.IsMatch("Hello1 Hello2", @"bHellob"); // yields false
    bool contains = Regex.IsMatch("Hello1 Hello", @"bHellob"); // yields true
    

    the b is a word boundary check, and used like above it will be able to match whole words only.

    • Edited by

      Wednesday, April 29, 2009 1:53 PM

    • Marked as answer by
      CodeSri
      Wednesday, April 29, 2009 1:54 PM

DISCLOSURE:
This article may contain affiliate links and any sales made through such links will reward us a small commission,
at no extra cost for you. Read more about Affiliate Disclosure here.

Check for existence of a substring into a string is a common requirement for programmers. Here I’m describing 3 functions to check if string contains specific words.

The top 3 functions available in PHP to check for word existence are:

  • strpos – Find the position of the first occurrence of a substring in a string.
  • strstr – Find the first occurrence of a string
  • preg_match – Perform a regular expression match

Each of them has variations for case-insensitive search, last occurrence etc. We are taking ‘strpos‘ into account as it’s faster and enough to find occurrence.

Check if string contains specific words

Suppose we have the requirement below:

$sentence = ‘How are you?’;

$word = ‘are’;&nbsp;

if ($sentence contains $word)

    echo ‘true’;

Then the correct way to write the statement will be: 

if (strpos($sentence, $word) !== false) {

    echo ‘true’;

}

/*

Or wrap inside another function for better code readability

// returns true if $needle is a substring of $haystack

function contains($needle, $haystack)

{

    return strpos($haystack, $needle) !== false;

}

*/

Note that the use of !== false is deliberate as if the needle (‘$word‘) you are searching for is at the beginning of the haystack (‘$sentence‘), it will return position 0. Since 0 is a valid offset and 0 is ‘falsey‘, we can’t use simpler constructs like !strpos($sentence, $word).

If you want to check if a string does not contain a word then rather changing ‘false‘ to ‘true‘, use complementary operator ‘===‘ like strpos($sentence, $word) === false.

Be aware that this will also return true for the string ‘Do you care?‘. If you need to deal with this situation then you can check the substring or word by either improving ‘strpos‘ condition or using ‘preg_match‘.

//needle is word to search and haystack is the string

function containsWord($needle, $haystack)

{

    $haystack = ‘ ‘.$haystack.‘ ‘;

    $needle = ‘ ‘.$needle.‘ ‘;

    return strpos($haystack, $needle) !== false;    

}

function containsWord($needle, $haystack)

{

    return !!preg_match(‘#b’ . preg_quote($needle, ‘#’) . ‘b#i’, $haystack);

}

The ‘preg_match‘ above will get fail with  sentences which are going to be anything that isn’t a-z, A-Z, 0-9, or _. That means digits and underscores are going to be counted as word characters and scenarios like these will return false:

  • The ‘are’ at the beginning of ‘area’
  • The ‘are’ at the end of ‘hare’
  • The ‘are’ in the middle of ‘fares’
  • The ‘are’ in ‘What _are_ you thinking?’
  • The ‘are’ in ‘lol u dunno wut those are4?’

The preg_match is slower and is not recommended to just check if string contains specific words.

In this code example we are going to learn how to find a specific word or text inside a string. For this example we will utilize the java.lang.String class. The String class provides a method called String.indexOf(). It takes an argument of a String, which is the sub string that we want to find in the other string. You can imagine the sub string as a needle that we are going to find in the haystack.

If the word found more than once in the string, the indexOf() method returns the first index of a sub string found in the specified string. If the sub string can’t be found this method returns -1. The index of string returns by this method begin at zero. It means that the first letter in the string have the index number 0.

Another way that we can use is the String.contains() method. This method introduced in JDK 1.5. The method simply return a boolean value which is true or false indicating whether the string in search is found in the haystack. Let’s see the snippet below:

package org.kodejava.lang;

public class StringContainsExample {
    public static void main(String[] args) {
        String haystack = "Kodejava - Learn Java by Examples";

        // Checks to see if the word "Java" is found in the haystack
        // variable.
        String needle = "Java";
        if (haystack.indexOf(needle) != -1) {
            System.out.println("Found the word " + needle +
                    " at index number " + haystack.indexOf(needle));
        } else {
            System.out.println("Can't find " + needle);
        }

        // Or use the String.contains() method if you are not interested
        // with the index of the word.
        if (haystack.contains(needle)) {
            System.out.println("Eureka we've found Java!");
        }
    }
}

Running the example gave you the following result:

Found the word Java at index number 17
Eureka we've found Java!
  • Author
  • Recent Posts

A programmer, runner, recreational diver, live in the island of Bali, Indonesia. Programming in Java, Spring, Hibernate / JPA. You can support me working on this project, buy me a cup of coffee ☕, every little bit helps, thank you 🙏

Views: 60,429

Like this post? Please share to your friends:
  • If syntax in excel formula
  • If string contains word java
  • If statements in word documents
  • If statements in excel with dates
  • If statements in excel with and or not