doudu2515 2010-09-08 01:27
浏览 117
已采纳

需要PHP中的Shunting Yard实现,解释和解析字符串执行数学比较并返回布尔结果

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.

For example:

  1. Sue types in "3*{mysalary}/9=10000"
  2. PHP splits this up into two expressions - explode('=',string);
  3. PHP takes my list of database fields, and replaces any "{}" delimited fields with the data (typecasted to int)
  4. PHP then evaluates the maths expression
  5. php then compares the left side to the right side
  6. boolean result produced.

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

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.

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.

Thanks.

Jason

  • 写回答

4条回答 默认 最新

  • duanfoumi5620 2010-09-08 07:52
    关注

    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)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)