PHP字符串计算

时间:2012-02-29 13:10:27

标签: php

我的问题是,

我们如何从PHP中的字符串中分离数字和运算符?

例如 - 2 + 2是什么?

那么,我们如何从该字符串中取出2 + 2,计算它并显示相应的结果?

感谢。

3 个答案:

答案 0 :(得分: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);

答案 1 :(得分: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 :(得分:0)

如果您想计算不考虑分组运算符(例如())或遵循运算/运算符优先顺序的内容,这是相当简单的。

如果您确实想要考虑这些因素,那么您必须愿意为无上下文语言编写解析器。

或者,你可以搜索那里有already been written

的图书馆