2012-04-09 63 views
0

我目前正在嘗試使用PhP來「解析」用戶輸入。 該頁面只是一個帶有一個輸入字段和提交按鈕的表單。php解析用戶輸入

我想要實現的結果是,如果用戶輸入「rand」,則使PhP回顯(rand(0,100)) 但是,如果用戶鍵入以下形式的某些內容:「rand int1-int2」it echo「rand(int1 ,INT2)」

我目前使用開關的情況下,打破用戶的輸入。

預先感謝您!

<form action="<?php $_SERVER['PHP_SELF'] ?>" method="POST"> 
    <input type="text" name="commande" /> 
    <input type="submit" name="submit" value="envoyer!" /> 
</form> 

<?php if (isset($_POST['commande'])) { 

    switch($_POST['commande']){ 
     case "hello": 
      echo"<h1> Hello </h1>"; 
     break; 
     case substr($_POST['commande'], 0, 4)=="rand": 
      echo(rand(1,100)); 
     break; 
     } 

    } 
?> 
+0

那麼什麼進步,你做這麼遠嗎?到目前爲止你有可能粘貼到目前爲止? – MrSaints 2012-04-09 15:21:59

+0

我添加了我到目前爲止的代碼。 – 2012-04-09 15:26:06

回答

1

可以使用explode實現這一目標。

<?php 
    $input = 'rand 1245'; 
    list($command, $arguments) = explode(' ', $input); 
    $arguments = explode('-', $arguments); 
    switch($command) { 
     case 'rand': 
      print_r($arguments);break; 
      $min = 0; 
      $max = 100; 
      if (count($arguments) == 2) { 
       $min = (int)$arguments[0]; 
       $max = (int)$arguments[1]; 
      } 

      echo rand($min, $max); 
      break; 

    } 
?> 

Live example

+0

噢,真好!我理解代碼的工作原理,但是如何將它與「switch」,「case x」,「break」形式結合起來呢?非常感謝您的幫助 ! – 2012-04-09 15:29:41

+0

我也忘了問一些問題。如果爆炸函數中的「分隔符」不存在,會發生什麼情況?謝謝 ! – 2012-04-09 15:31:54

+0

@AwakeZoldiek我已更新我的代碼以使用'switch'語句。如果分隔符不存在,它將只返回整個字符串,這就是爲什麼你想把檢查放在像我的'if(count($ arguments)...' – 2012-04-09 15:49:20