1

配列キーを検索するコードがありますが、メッセージが正確なメッセージである場合にのみ、strposを使用してメッセージを検出できるようにしたいのですが、その方法がわかりません。

私のコード:

$message = $_POST['message'];
$responses = array("hi" => "whats up?");
if (array_key_exists($message,$responses)){
$msg = strtolower($message);
$answer = $responses[$msg];
echo $answer;
}

したがって、これは、投稿されたデータ全体が「こんにちは」である場合にのみ機能します。strposを使用して、どこでもhiを検出できるようにしたいのですが、どうすればよいですか?

4

2 に答える 2

1

100%確信があるわけではありませんが、これでよろしいですか?

$foundKey = null;
foreach ($responses as $key => $value) {
    if (strpos($message, $key) !== false) {
        $foundKey = $key;
        break;
    }
}
if ($foundKey !== null) {
    echo "Found key: " . $responses[$key];
}

編集

大文字と小文字を区別しないバージョンが必要な場合は、もちろん、代わりにこれを使用できます。

$foundKey = null;
foreach ($responses as $key => $value) {
    if (stripos($message, $key) !== false) {
        $foundKey = strtolower($key);
        break;
    }
}
if ($foundKey !== null) {
    echo "Found key: " . $responses[$key];
}
于 2012-08-13T06:40:47.537 に答える
0

strpos(firststring,secondstring,startposition[Optional]) 関数は num を返します。num>=0 の場合は、最初の文字列の 2 番目の文字列を意味します。

$message = $_POST['message'];
$responses = array("hi" => "whats up?");
if (strpos($message,$responses)>=0){
$msg = strtolower($message);
$answer = $responses[$msg];
echo $answer;
}
于 2012-08-13T06:43:34.663 に答える