私の質問は、PHPの文字列計算
PHPの文字列から数字と演算子を分離するにはどうすればよいですか?
例:2 + 2とは何ですか?
文字列から2 + 2を取り出し、計算して、適切な結果を表示するにはどうすればよいですか?
ありがとうございました。
私の質問は、PHPの文字列計算
PHPの文字列から数字と演算子を分離するにはどうすればよいですか?
例:2 + 2とは何ですか?
文字列から2 + 2を取り出し、計算して、適切な結果を表示するにはどうすればよいですか?
ありがとうございました。
かなり複雑な数式を扱える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;
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);
ereg_replace()は推奨されていません –
アカウントグループ化事業者になりません、何かを計算したい場合(例えば(
と)
など)や操作/演算子の優先順位の順序に従う、これはありますかなり簡単。
しかし、これらのことを考慮する必要がある場合は、コンテキストフリーの言語用のパーサーを作成する必要があります。
OR、あなたはのalready been written
が重複する可能性がありそこにライブラリを検索できます[?PHPで文字列として渡された式を評価する方法](http://stackoverflow.com/q/1015242/367456 ) – hakre