使用eval从字符串计算数学表达式

Lan*_*ler 21 php math eval

我想从字符串中计算数学表达式.我已经读过,解决方法是使用eval().但是当我尝试运行以下代码时:

<?php

$ma ="2+10";
$p = eval($ma);
print $p;

?>
Run Code Online (Sandbox Code Playgroud)

它给了我以下错误:

解析错误:语法错误,意外的$ end在C:\ xampp\htdocs\eclipseWorkspaceWebDev\MandatoryHandinSite\tester.php(4):eval()'代码在第1行

有人知道这个问题的解决方案.

Roc*_*mat 48

虽然我不建议使用eval它(它不是解决方案),但问题是eval需要完整的代码行,而不仅仅是片段.

$ma ="2+10";
$p = eval('return '.$ma.';');
print $p;
Run Code Online (Sandbox Code Playgroud)

应该做你想做的.


更好的解决方案是为数学表达式编写tokenizer/parser.这是一个非常简单的基于正则表达式的例子,给你一个例子:

$ma = "2+10";

if(preg_match('/(\d+)(?:\s*)([\+\-\*\/])(?:\s*)(\d+)/', $ma, $matches) !== FALSE){
    $operator = $matches[2];

    switch($operator){
        case '+':
            $p = $matches[1] + $matches[3];
            break;
        case '-':
            $p = $matches[1] - $matches[3];
            break;
        case '*':
            $p = $matches[1] * $matches[3];
            break;
        case '/':
            $p = $matches[1] / $matches[3];
            break;
    }

    echo $p;
}
Run Code Online (Sandbox Code Playgroud)

  • 用以下内容替换模式对我来说很有效(允许数字、空格和小数) - 请注意,它将匹配带有空格的数字(即“201.5 + 11 2012 = 212.5”,因此数学无法完全工作正确地不去除这些空格(通过围绕 `$matches[1]` 和 `$matches[3]` 或类似的 `str_replace`。这将完全取决于您的使用 - 这对我的需求有效。`/( [\d\.\s]+)([\+\-\*\/])([\d\.\s]+)/` (2认同)

cla*_*rkk 32

看看这个..

我在会计系统中使用它,你可以在数量输入字段中编写数学表达式.

例子

$Cal = new Field_calculate();

$result = $Cal->calculate('5+7'); // 12
$result = $Cal->calculate('(5+9)*5'); // 70
$result = $Cal->calculate('(10.2+0.5*(2-0.4))*2+(2.1*4)'); // 30.4
Run Code Online (Sandbox Code Playgroud)

class Field_calculate {
    const PATTERN = '/(?:\-?\d+(?:\.?\d+)?[\+\-\*\/])+\-?\d+(?:\.?\d+)?/';

    const PARENTHESIS_DEPTH = 10;

    public function calculate($input){
        if(strpos($input, '+') != null || strpos($input, '-') != null || strpos($input, '/') != null || strpos($input, '*') != null){
            //  Remove white spaces and invalid math chars
            $input = str_replace(',', '.', $input);
            $input = preg_replace('[^0-9\.\+\-\*\/\(\)]', '', $input);

            //  Calculate each of the parenthesis from the top
            $i = 0;
            while(strpos($input, '(') || strpos($input, ')')){
                $input = preg_replace_callback('/\(([^\(\)]+)\)/', 'self::callback', $input);

                $i++;
                if($i > self::PARENTHESIS_DEPTH){
                    break;
                }
            }

            //  Calculate the result
            if(preg_match(self::PATTERN, $input, $match)){
                return $this->compute($match[0]);
            }
            // To handle the special case of expressions surrounded by global parenthesis like "(1+1)"
            if(is_numeric($input)){
                return $input;
            }

            return 0;
        }

        return $input;
    }

    private function compute($input){
        $compute = create_function('', 'return '.$input.';');

        return 0 + $compute();
    }

    private function callback($input){
        if(is_numeric($input[1])){
            return $input[1];
        }
        elseif(preg_match(self::PATTERN, $input[1], $match)){
            return $this->compute($match[0]);
        }

        return 0;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 因为,在php 7.2中折旧了create_function,所以如何重写compute()函数?我不想使用eval但这个接缝工作:private function compute($ input){return 0 + eval('return'.$ input.';');} (2认同)

Div*_*ega 7

我最近创建了一个提供math_eval帮助函数的 PHP 包。它完全可以满足您的需要,而无需使用可能不安全的eval功能。

您只需传入数学表达式的字符串版本,它就会返回结果。

$two   = math_eval('1 + 1');
$three = math_eval('5 - 2');
$ten   = math_eval('2 * 5');
$four  = math_eval('8 / 2');
Run Code Online (Sandbox Code Playgroud)

您还可以传入变量,如果需要,变量将被替换。

$ten     = math_eval('a + b', ['a' => 7, 'b' => 3]);
$fifteen = math_eval('x * y', ['x' => 3, 'y' => 5]);
Run Code Online (Sandbox Code Playgroud)

链接: https: //github.com/langleyfoxall/math_eval


Mar*_*dor 6

当你无法控制字符串参数时,使用eval函数是非常危险的。

尝试使用Matex进行安全的数学公式计算。