How to check multiple words per line? (returns true, there is at least one of these words)

I have a line like this:

$str = "it is a test";

I want to check this out for these words: it, test. I want it to return trueif there is at least one of these words in a string.

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

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

How can i do this?

0
source share
3 answers

just checking with preg_match, you can add many different words to the template, just use the separator |between the words

$str = "it is a test";
if (preg_match("[it|test]", $str) === 1)
{
    echo "it matches";
}

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

$str = "你好 abc efg";
if (preg_match("/\b(你好|test)\b/u", $str) === 1)
{
    echo "it matches";
}

, \b ,

+3

- explode, :

$str = "it is a test"; // Remember your quotes!

$keywords = array ('it', 'test');

$str_array = explode(" ", $str);
$foundWords = [];
foreach ($keywords as $key)
{
    if (in_array($key, $str_array))
    {
        $foundWords[] = $key;
    }
}
foreach($foundWords as $word)
{
    print("Word '{$word}' was found in the string '{$str}'<br />");
}

:

"" " "
Word 'test' " "

, , , foreach.

- :

$keywords = array ('it', 'test');
echo (strpos($srt, $keywords[0]) ? "true" : "false");
echo (strpos($srt, $keywords[1]) ? "true" : "false");
+1

, , . , strpos ?

:

$array = ('it', 'test');
for($i=0;$i<$array.length;$i++){

//here the strpos Method but with $array[$i] }

0

Source: https://habr.com/ru/post/1615572/


All Articles