需要在PHP中使用Shunting Yard实现,解释和解析字符串以执行数学比较并返回布尔结果 [英] Shunting Yard implementation in PHP needed, interpret and parse a string perform a mathematical comparison and return a boolean result

查看:88
本文介绍了需要在PHP中使用Shunting Yard实现,解释和解析字符串以执行数学比较并返回布尔结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找可以解释php中的字符串并执行简单数学计算,然后返回关于表达式是true还是false的布尔结果的东西.

I'm looking for something that can interpret a string in php and perform simple math calculation, and then return a boolean result as to whether the expression is true or false.

例如:

  1. 起诉类型为"3 * {mysalary}/9 = 10000"
  2. PHP将其分为两个表达式-explode('=',string);
  3. PHP接收了我的数据库字段列表,并用数据(类型转换为int)替换了所有用"{}"分隔的字段
  4. PHP然后评估数学表达式
  5. php然后将左侧与右侧进行比较
  6. 产生布尔结果.

这听起来可能很复杂,但只需要非常简单即可.这里是约束: 1/数学运算符固定为:+-/* 2/比较运算符固定为:=>< > =< = 3/不需要浮点比较,所有操作都可以在整数级别完成.因此,如果需要,可以对任何除法取整,也可以仅对最终结果取整

It may sound complex but it only needs to be very simple. Here are the constraints: 1/ mathematical operators are fixed to: + - / * 2/ comparison operators are fixed to: = > < >= <= 3/ do not need floating point comparisons, everything can be done at an integer level. So any divisions can be rounded if need be or simply just round the final result

将永远只有两个表达式,只有一个比较运算符. 如果根本没有任何错误,我们将返回false.

There will only ever be two expressions, with one comparison operator. If there is any sort of error at all we will just return false.

有人见过可以做到这一点的东西吗?我知道我可以做点什么,但是为什么要重新发明轮子呢?

Has anyone seen something that can do this already? I know I can make something but why re-invent the wheel right?

如果您什么都没看,您会列出一些在构建时可以想到的陷阱"或警告.

If you haven't seen anything do you care to list some "gotcha's" or caveat's that you can think of when building this.

阅读更多内容后,我意识到我可以使用调车场算法.有没有人用PHP实现此功能?

After reading some more I realise I could use the shunting yard algorithm. Does anyone have an implementation of this in PHP?

我知道评估可能是执行此操作的简便方法,但是,令我担心的是,用户可能很容易使用此方法破坏某些内容或导致语法错误.我宁愿不将其包含在解决方案中,或者如果这样做,则需要严格控制其使用方式.

I am aware the eval could be an easy method to perform this, however, it concerns me that the user could very easily break something using this method or cause syntax errors. I'd rather not include it in the solution, or if i do then it'd need to tightly control how it is used.

谢谢.

Jason

推荐答案

看看

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)

这篇关于需要在PHP中使用Shunting Yard实现,解释和解析字符串以执行数学比较并返回布尔结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆