2012-02-29 23 views
-8

私の質問は、PHPの文字列計算

PHPの文字列から数字と演算子を分離するにはどうすればよいですか?

例:2 + 2とは何ですか?

文字列から2 + 2を取り出し、計算して、適切な結果を表示するにはどうすればよいですか?

ありがとうございました。

+0

が重複する可能性がありそこにライブラリを検索できます[?PHPで文字列として渡された式を評価する方法](http://stackoverflow.com/q/1015242/367456 ) – hakre

答えて

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()は推奨されていません –

0

アカウントグループ化事業者になりません、何かを計算したい場合(例えば()など)や操作/演算子の優先順位の順序に従う、これはありますかなり簡単。

しかし、これらのことを考慮する必要がある場合は、コンテキストフリーの言語用のパーサーを作成する必要があります。

OR、あなたはのalready been written

関連する問題