dongmei9961 2015-07-10 13:13
浏览 143
已采纳

查找字符串中与多个数组键匹配的所有单词

I have an array like array("red","blue","azure"...) and i have a string that might contain some of the words. The task is to get array of all the matching colors from the given string.

String example: "Red fox met a blue whale". It should output ["red","blue"]

Give me a starting point to go on with.

Thanks, Martti

  • 写回答

5条回答 默认 最新

  • douhuai2015 2015-07-10 13:24
    关注

    str_word_count() with a format argument of 1 or 2, then an array_intersect().... but watch out for case-sensitivity, force it all to lower case first

    $matchWords = array("red","blue","azure");
    $sentence = "Red fox met a blue whale";
    
    $result = array_intersect(
        $matchWords,
        str_word_count(strtolower($sentence), 1)
    );
    
    var_dump($result);
    

    Demo

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?