Find answer to string equation without using eval()

我与影子孤独终老i 提交于 2019-12-04 17:03:25

Math expressions aren't regular. They're context-free.

Your best bet is to parse them using well-known math parsing algorithms like the shunting yard algorithm. All you have to worry about is implementing the algorithm in PHP. You might even be able to find PHP implementations of it online.

Just in case anybody's interested here is the algorithm I came up with in PHP for producing Reverse Polish Notation

function convertToRPN($equation)

{
    $equation = str_replace(' ', '', $equation);
    $tokens = token_get_all('<?php ' . $equation);
    $operators = array('*' => 1, '/' => 1, '+' => 2, '-' => 2);
    $rpn = '';
    $stack = array();
    $size = count($tokens);                                                 
    for($i = 1; $i < $size; $i++) {
        if(is_array($tokens[$i])) {
            $rpn .= $tokens[$i][1] . ' ';
        } else {
            if(empty($stack) || $tokens[$i] == '(') {
                $stack[] = $tokens[$i];
            } else {
                if($tokens[$i] == ')') {
                    while(end($stack) != '(') {
                        $rpn .= array_pop($stack);
                    }
                    array_pop($stack);
                } else {
                    while(!empty($stack) && end($stack) != '(' && $operators[$tokens[$i]] >= $operators[end($stack)]) {
                        $rpn .= array_pop($stack);
                    }
                    $stack[] = $tokens[$i];
                }
            }
        }
    }

    while(!empty($stack)) {
        $rpn .= array_pop($stack);
    }

    return $rpn;
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!