【发布时间】:2014-11-20 09:33:46
【问题描述】:
我使用 PHP 代码制作了一个问答机器人。它的工作方式是用户必须在提供的“搜索”栏中输入问题。单击“提交”按钮后,程序将搜索特定关键字并回复所提出的问题。但是,如果问的问题中有多个关键字,我如何只显示一个回复?另外,当用户不问没有特定关键字的问题时,如何显示错误消息?
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 个答案后立即退出
while循环,方法是在您之前初始化为false的特定变量(例如:$exit == true)上添加额外条件循环并在打印后的每个case语句中将此值设置为true。关于你的第二个问题,这也很方便:离开循环后,如果这个变量是true,你知道你回答了这个问题,如果它仍然是false,你知道你无法理解它并且可以显示适当的消息。 -
strtok () ?? php 还是 C++?
-
@CodingAnt 我正在使用 PHP 代码。
-
@Bartdude 你能提供代码吗?这对我有很大帮助。谢谢。
-
当然不是,这不是 SO 的目标。你自己试试吧,这真的没什么大不了的,真的可以用我描述的简单步骤来总结。
标签: php while-loop switch-statement stringtokenizer