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

前端 未结 5 1710
死守一世寂寞
死守一世寂寞 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:11

    Assuming the formatting and only that you care if any (not which) of the keywords exist, you could try something like:

    $keywords = array( "dog", "cat" );
    
    // get a valid regex
    $test = "(\b".implode( "\b)|(\b", $keywords )."\b)";
    
    if( preg_match( $test, "there is a dog chasing a cat down the road" ) )
        print "keyword hit";
    

提交回复
热议问题