2012-02-29 81 views
-8

我的問題是,PHP字符串計算

我們怎樣才能從PHP中的字符串中分離出數字和運算符?

例如 - 什麼是2 + 2?

那麼,我們如何從字符串中取出2 + 2,並對其進行計算並顯示出合適的結果呢?

謝謝。

+0

的可能的複製:[?如何評估式,如同在PHP字符串傳遞(http://stackoverflow.com/q/1015242/367456 ) – hakre 2013-09-25 06:01:03

回答

1

看看PHPClasses上的evalMath類,它可以處理相當複雜的公式。

或者:

$string = '2 + 2'; 
list($operand1,$operator,$operand2) = sscanf($string,'%d %[+\-*/] %d'); 
switch($operator) { 
    case '+' : 
     $result = $operand1 + $operand2; 
     break; 
    case '-' : 
     $result = $operand1 - $operand2; 
     break; 
    case '*' : 
     $result = $operand1 * $operand2; 
     break; 
    case '/' : 
     $result = $operand1/$operand2; 
     break; 
} 
echo $result; 
2
function calculate_string($mathString) { 
    $mathString = trim($mathString);  // trim white spaces 
    $mathString = ereg_replace ('[^0-9\+-\*\/\(\) ]', '', $mathString); 

    $compute = create_function("", "return (" . $mathString . ");"); 
    return 0 + $compute(); 
} 

$string = " (1 + 1) * (2 + 2)"; 
echo calculate_string($string); 
+0

ereg_replace()已棄用 – 2012-02-29 13:28:14

0

如果你要計算的東西,不考慮分組運算符(如())或按照操作/運算符的優先順序,這是一個非常坦率的。

如果您確實想要考慮這些因素,那麼您必須願意爲上下文無關語言編寫解析器。

或者,你可以搜索庫,在那裏,有already been written