PHP字符串计算
我的问题是, 在PHP中,如何将数字和运算符从字符串中分离出来 什么是2+2 那么,我们如何从该字符串中取出2+2,计算它,并显示适当的结果呢 谢谢。看一看关于PHPClasses的类,它可以处理相当复杂的公式 或者:PHP字符串计算,php,Php,我的问题是, 在PHP中,如何将数字和运算符从字符串中分离出来 什么是2+2 那么,我们如何从该字符串中取出2+2,计算它,并显示适当的结果呢 谢谢。看一看关于PHPClasses的类,它可以处理相当复杂的公式 或者: $string = '2 + 2'; list($operand1,$operator,$operand2) = sscanf($string,'%d %[+\-*/] %d'); switch($operator) { case '+' : $resul
$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);