PHP在字符串中查找单词

我有以下关键字。我希望最终答案(可能是 answer_1、answer_2、answer_3)是包含“问题”中的关键字的答案。


$question = 'how old are you'


$key_word_1 = array('old', 'are');

$answer_1 = 'this is my age';


$key_word_2 = array('yes', 'no');

$answer_2 = 'this is a question';


$key_word_3 = array('tall', 'short');

$answer_3 = 'this are my measures';


$key_word_4 = array('back', 'blue');

$answer_4 = 'My colorus';


echo $final_answer;

'this is my age' . #----> because 'old' and 'are' are contained in $question


慕运维8079593
浏览 140回答 1
1回答

小唯快跑啊

我会这样做(使用array_intersect):$question = 'how old are you';$question_array = explode(' ',$question);$answers_array[0]['keywords'] = array('old', 'are');$answers_array[0]['answer'] = 'this is my age';$answers_array[1]['keywords'] = array('yes', 'no');$answers_array[1]['answer'] = 'this is a question';$answers_array[2]['keywords'] = array('tall', 'short');$answers_array[2]['answer'] = 'this are my measures';$answers_array[3]['keywords'] = array('back', 'blue');$answers_array[3]['answer'] = 'My colorus';foreach($answers_array as $key=> $answer){    if(sizeof(array_intersect($answers_array[$key]['keywords'], $question_array)) == sizeof($answers_array[$key]['keywords']))    {        $final_answer = $answers_array[$key]['answer'];    }}echo $final_answer;
打开App,查看更多内容
随时随地看视频慕课网APP