2013-07-08 28 views
0

我正在爲一個IRC機器人的數學函數,但我似乎無法得到這個數字的力量,即5 ** 2,目標是保持它作爲儘可能安全,因爲它確實使用eval,並且除此之外還能夠進行大量的通用數學計算。 現在,這就是我所擁有的。有沒有更好/更有效的方法? 在此先感謝。PHP的Eval數學函數爲機器

case ':$math': 
       $input = rtrim($this->get_message()); // grabbing the user input 
       $input = preg_replace('/[0-9+*%.\/-(\*\*)]/', '', $input); 
       $sum = $this->do_math($input); // store the return of our input passed through the do_math function into $sum 
       if($sum == "NULL") { 
        break; 
       } 
       else { 
        $this->send_message("The value is: ".$sum); // echo the value 
       } 
       break; 





    function do_math($input) { 
     $result=eval("return ($input);"); // using eval to preform math on the specified input 
     if($result == NULL) { 
      $this->send_message("Invalid characters were assigned in the math function!"); 
      return "NULL"; 
      break; 
     } 
     else { 
      return $result; // return the sum 
     } 
    } 
+0

在php中沒有**運算符...您應該使用pow函數代替 – Orangepill

回答

1

正如我在評論說沒有**運營商在PHP中,pow函數應改爲使用...你可以做的,雖然效仿的是在輸入扔另一個的preg_replace。

$input = rtrim($this->get_message()); // grabbing the user input 
$input = preg_replace('/([0-9.]+)\*\*([0-9.]+)/', 'pow($1, $2)', $input); 
$sum = $this->do_math($input); 
+0

爲此,我必須刪除第一個preg_replace。感謝您的快速回復! – Singularity