My question is,
How can we separate out digits and operators from a string in PHP?
Eg - What is 2 + 2?
So, how can we take the 2 + 2 out from that string, CALCULATE it, and display the appropriate result?
Thanks.
My question is,
How can we separate out digits and operators from a string in PHP?
Eg - What is 2 + 2?
So, how can we take the 2 + 2 out from that string, CALCULATE it, and display the appropriate result?
Thanks.
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);
Take a look at the evalMath class on PHPClasses, which can handle quite complex formulae.
Alternatively:
$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;
If you want to calculate something that does not take into account grouping operators (such as (
and )
) or follow the order of operations / operator precedence, this is a fairly straightforward.
If however you do want to take those things into account, then you have to be willing to write a parser for a context free language.
OR, you could search for a library out there that has already been written