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

前端 未结 5 1703
死守一世寂寞
死守一世寂寞 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条回答
  •  -上瘾入骨i
    2021-02-06 20:22

    Working off eWolf's idea...

    foreach($keywords as &$keyword) {
      $keyword = preg_quote($keyword);
    }
    
    $regex = "/(". implode('|', $keywords) .")/";
    
    return preg_match($regex, $str);
    

    You don't have to check for boundaries if you don't want to, but if you do just surround the group (the () characters) with \b then it'll match only a given word. And you'll want to make sure all the array's members are preg_quoted, for safety.

提交回复
热议问题