Skip to content
Advertisement

Check if one of multiple words exists in the string?

I have a string like this:

$str = "it is a test";

I want to check it for these words: it, test. I want to it returns true if there is at least one of those words in the string.

Here is what I did: (though it does not work)

$keywords = array ('it', 'test');
if(strpos($str, $keywords) !== false){ echo 'true';}
else echo 'false';

How can I do that?

Advertisement

Answer

Simply checking using preg_match(), you can add many different words in the pattern, just use a separator | in between words.

The following will match partial words, so larger words like pit, testify, itinerary will be matched. The pattern is also case-sensitive, so It and Test will not be matched.

$str = "it is a test";
if (preg_match("/it|test/", $str))
{
    echo "a word was matched";
}

Sorry, I didn’t know that you were dealing with other languages, you can try this:

$str = "你好 abc efg";
if (preg_match("/b(你好|test)b/u", $str))
{
    echo "a word was matched";
}

I also need to mention that b means word boundary, so it will only matches the exact words.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement