为了账号安全,请及时绑定邮箱和手机立即绑定

PHP在字符串中查找单词

PHP在字符串中查找单词

PHP
慕运维8079593 2022-06-17 16:39:38
我有以下关键字。我希望最终答案(可能是 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
查看完整描述

1 回答

?
小唯快跑啊

TA贡献1863条经验 获得超2个赞

我会这样做(使用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;


查看完整回答
反对 回复 2022-06-17
  • 1 回答
  • 0 关注
  • 139 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信