2013-06-20 126 views
0

所以我有這個命令處理:AJAX聊天命令 - 如果命令不存在,回顯錯誤

$ message =輸入的消息。

public function handleCommands($message, $username) 
    { 
     //Variables we're going to use 
     $space = strpos($message, ' '); # The first space. 
     $command = trim(substr($message, 1, $space)); # The command after the slash 
     $name = substr($message, $space + 1); # The name after the command. 


     switch ($command) 
     { 
      case 'ban': 
       $this->ban($name, $username); 
      break; 

      case 'prune': 
       $this->prune($username); 
      break; 

      case '': 
       echo 'Please use a command!'; 
      break; 

      case 'test': 
       try 
       { 
        $this->test($name); 
       } 
       catch (exception $r) 
       { 
        echo $r->getMessage(); 
       } 
      break; 
     } 
    } 

這基本上會檢查命令。

$ command =斜槓後面輸入的單詞(「/」)。

你能看到

case '': 

這基本上會檢查是否有斜線後沒有命令。

問題:我希望系統檢查以及,如果命令存在的情況下。

例如:

用戶寫道:

/你好

但該命令不存在,考慮到我們只有情況下 '禁令',情況 '修剪',情況 '測試'和案例''。

沒有大小寫'hello',所以會引發錯誤。 是否有這樣的功能?我怎樣才能做到這一點?

回答

2

我相信你正在尋找的是一個default:情況。

例子:

<?php 
switch ($i) { 
    case 0: 
     echo "i equals 0"; 
     break; 
    case 1: 
     echo "i equals 1"; 
     break; 
    case 2: 
     echo "i equals 2"; 
     break; 
    default: 
     echo "i is not equal to 0, 1 or 2"; 
} 
?> 

編輯: 的問題固定的版本,這是聊起:http://privatepaste.com/bd34e7e63b

+0

出於某種原因,當我寫在我的聊天/ blablabla,它激活的情況下「case」:「,但是當我添加一個像」/ blablabla「這樣的空間時,它可以工作。任何想法爲什麼? –

+0

'trim(substr($ message,1,$ space));'正在擦除整個變量。將它替換爲'$ command = substr(strrchr($ message,'/'),1);'你應該得到你想要的。假設你只是在尋找數據sans'/'。 –

+0

噢,偉大的人!如此多的功能我沒有使用,我現在肯定會照顧他們。 –

1

使用的情況下默認:

switch ($command) 
    { 
     case 'ban': 
      $this->ban($name, $username); 
     break; 

     case 'prune': 
      $this->prune($username); 
     break; 

     case '': 
      echo 'Please use a command!'; 
     break; 

     case 'test': 
      try 
      { 
       $this->test($name); 
      } 
      catch (exception $r) 
      { 
       echo $r->getMessage(); 
      } 
     break; 

     default: 
      echo "That command does not exist."; 
    }