Evaluate Arithmetic Strings

I was recently working on a finance ledger project which required users to be able to enter transaction splits. I wanted them to be able to do math in the actual split amount fields instead of having to load up a separate calculator. So, I decided to harness the power of PHP's eval function and now make an Ajax call from the form whenever the split amount began with an equals sign.

I didn't include all of that here, but here's the one core function that I used. Before I thought of using eval, I was trying to recreate the wheel on my own and it quickly got too complicated. There are obviously lots of security concerns with eval, but by stripping out all of the non-numeric and operation characters with regex, they are mitigated.

Here's a working example. The code above is snagged directly from that page. Check it out.

Any questions? Suggestions? Stick them in the comments below.



This post was published on December 23rd, 2011 by Robert James Reese in PHP Before using any of the code or other content in this post, you must read and agree to our terms of use.