PHP - Find if any of the keywords in an array exist in a string

前端 未结 5 1702
死守一世寂寞
死守一世寂寞 2021-02-06 19:32

Basically, I have an array of keywords, and a piece of text. I am wondering what would be the best way to find out if any of those keywords are present in the text, bearing in m

5条回答
  •  情深已故
    2021-02-06 20:05

    Depending on the size of the string You could use a hash to make it faster.

    First iterate the text. For each word, assign it to an array:

     foreach (preg_split("/\s/", $text) as $word)
     {
         $string[$word] = 1;
     }
    

    Then iterate the keywords checking the $string:

     foreach ($keywords as $keyword)
     {
         if (isset($string[$keyword]))
         {
             // $keyword exists in string
         }
     }
    

    EDIT If your text is much smaller than your keywords, do it backwards, check the keywords for each word in the text. This would likley be faster than the above if the text is pretty short.

     foreach (preg_split("/\s/", $text) as $word)
     {
        if (isset($keywords[$word]))
        {
            //might be faster if sizeof($text) < sizeof($keywords)
        }
    }
    

提交回复
热议问题