Shunting Yard implementation in PHP needed, interpret and parse a string perform a mathematical comparison and return a boolean result

怎甘沉沦 提交于 2019-11-28 14:04:34

Take a look at the evalMath class on PHPClasses. This should do pretty much everything that you want, including variable substitution (such as setting a value for "mysalary" in your example before evaluating the expression)

There is an expression parser engine (implementations for JavaScript+Node, PHP, Python and ActionScript), on github Xpresion (ps. i'm the author)

The engine is quite flexible and configurable, one can create parsers that parse any expression which also includes user-defined variables, user-defined functions, polymorphic operators and general n-ary operators (eg. ternary if-then-else)

The algorithm is quite general (one could say, a generalised variation of Shunting Yard algorithm)

The approach I'd take is:

  1. Tokenize the expression
  2. Parse it into an abstract syntax tree
  3. Perform variable substitutions (see eager evaluation)
  4. Calculate the result

Now...

  • The shunting-yard algorithm is a way to do steps 1 and 2.
  • You can check if the expression is syntactically correct after the 2nd step
  • How you calculate the result will depend on how the AST is built.

The hardest step is the 2nd; you have to consider operator precedence, parentheses and other things, but there's plenty of literature on that (you can even just follow that wikipedia link)

why dont you simply perform variables replacements, and then do a preg_replace("/[^0-9+-*\/]/", '', $inputString), and then use either eval() or create_function()? If you use this you MUST make sure that possibly unsafe "statements" are removed, that's why i used preg_replace, so it would remove any literal string

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