响应机器人使用关键字

时间:2014-11-20 09:33:46

标签: php while-loop switch-statement stringtokenizer

我使用PHP代码创建了一个q& a bot。它的工作方式是用户必须在提供的“搜索”栏中键入问题。点击“提交”按钮后,程序将搜索特定的关键字并回复询问的问题。但是,如果问题中有多个关键字,如何只显示一个回复?此外,如果用户在没有特定关键字的情况下没有提出问题,如何显示错误消息?

if (isset($_GET['searchterm']))
{
$question = $_GET['searchterm'];
echo "<b>$question</b>";
echo "<br />";

$token = strtok($question, " ");

while($token !== false)
{
$token = strtok(" ");

switch ($token) {
case "hot":
    print "It is now ".$data['main']['temp']. " °C"." hot"."<br>";
    break;
case "cold":
    print "It is ".$data['main']['temp']. " °C"."<br>";
    break;
 case "warm":
    print "It is ".$data['main']['temp']. " °C"." warm"."<br>";
    break;
case "cool":
    print "The temperature is ".$data['main']['temp']. " °C"." cool"."<br>";
    break;
case "temperature":
    print "The temperature now is ".$data['main']['temp']. " °C"."<br>";
    break;
case "current":
    print "The current temperature is ".$data['main']['temp']. " °C"."<br>";
    break;
case "weather":
    print "We are now having ".$data['weather'][0]['main']."<br>";
    break;  
case "wind":
    print "The wind speed is currently ".$data['wind']['speed']. " m/s"."<br>";
    break;      
}
}   
}
else {
    print "Sorry, we did not understand your question.";
}

1 个答案:

答案 0 :(得分:0)

Use default conditon on your code:
switch ($i) {
    switch ($token) 
        {
            case "hot":
                print "It is now ".$data['main']['temp']. " °C"." hot"."<br>";
                break;
            case "cold":
                print "It is ".$data['main']['temp']. " °C"."<br>";
                break;
             case "warm":
                print "It is ".$data['main']['temp']. " °C"." warm"."<br>";
                break;
            case "cool":
                print "The temperature is ".$data['main']['temp']. " °C"." cool"."<br>";
                break;
            case "temperature":
                print "The temperature now is ".$data['main']['temp']. " °C"."<br>";
                break;
            case "current":
                print "The current temperature is ".$data['main']['temp']. " °C"."<br>";
                break;
            case "weather":
                print "We are now having ".$data['weather'][0]['main']."<br>";
                break;  
            case "wind":
                print "The wind speed is currently ".$data['wind']['speed']. " m/s"."<br>";
                break;
            default:
            print "wrong question";
        }
}