How to mathematically evaluate a string like "2-1" to produce "1"?

36,702

Solution 1

I know this question is old, but I came across it last night while searching for something that wasn't quite related, and every single answer here is bad. Not just bad, very bad. The examples I give here will be from a class that I created back in 2005 and spent the past few hours updating for PHP5 because of this question. Other systems do exist, and were around before this question was posted, so it baffles me why every answer here tells you to use eval, when the caution from PHP is:

The eval() language construct is very dangerous because it allows execution of arbitrary PHP code. Its use thus is discouraged. If you have carefully verified that there is no other option than to use this construct, pay special attention not to pass any user provided data into it without properly validating it beforehand.

Before I jump in to the example, the places to get the class I will be using is on either PHPClasses or GitHub. Both the eos.class.php and stack.class.php are required, but can be combined in to the same file.

The reason for using a class like this is that it includes and infix to postfix(RPN) parser, and then an RPN Solver. With these, you never have to use the eval function and open your system up to vulnerabilities. Once you have the classes, the following code is all that is needed to solve a simple (to more complex) equation such as your 2-1 example.

require_once "eos.class.php";
$equation = "2-1";
$eq = new eqEOS();
$result = $eq->solveIF($equation);

That's it! You can use a parser like this for most equations, however complicated and nested without ever having to resort to the 'evil eval'.

Because I really don't want this only only to have my class in it, here are some other options. I am just familiar with my own since I've been using it for 8 years. ^^

Wolfram|Alpha API
Sage
A fairly bad parser
phpdicecalc

Not quite sure what happened to others that I had found previously - came across another one on GitHub before as well, unfortunately I didn't bookmark it, but it was related to large float operations that included a parser as well.

Anyways, I wanted to make sure an answer to solving equations in PHP on here wasn't pointing all future searchers to eval as this was at the top of a google search. ^^

Solution 2

$operation='2-1';
eval("\$value = \"$operation\";");

or

$value=eval("return ($operation);");

Solution 3

This is one of the cases where eval comes in handy:

$expression = '2 - 1';
eval( '$result = (' . $expression . ');' );
echo $result;

Solution 4

You can use BC Math arbitrary precision

echo bcsub(5, 4); // 1
echo bcsub(1.234, 5); // 3
echo bcsub(1.234, 5, 4); // -3.7660

http://www.php.net/manual/en/function.bcsub.php

Solution 5

In this forum someone made it without eval. Maybe you can try it? Credits to them, I just found it.

function calculate_string( $mathString )    {
    $mathString = trim($mathString);     // trim white spaces
    $mathString = ereg_replace ('[^0-9\+-\*\/\(\) ]', '', $mathString);    // remove any non-numbers chars; exception for math operators

    $compute = create_function("", "return (" . $mathString . ");" );
    return 0 + $compute();
}

$string = " (1 + 1) * (2 + 2)";
echo calculate_string($string);  // outputs 8  
Share:
36,702
Nikola
Author by

Nikola

Director of Engineering at Teltech, where we make innovative communications apps. Come and see what I write about on my blog. My book on MEAN stack. My book about Ionic framework - step by step from idea through prototyping to the app stores If you happen to fancy titles, I have a masters degree in computing from FER. My 200th post: What have I learned from writing 200 posts on my blog. My 300th post: After writing 300 posts, this is why I think you should start blogging too Meetup organizer. Podcast host. "There's no short term solution for a long term result." G. Plitt "Everything around you that you call life was made up by people that were no smarter than you." S. Jobs

Updated on July 21, 2021

Comments

  • Nikola
    Nikola almost 3 years

    I was just wondering if PHP has a function that can take a string like 2-1 and produce the arithmetic result of it?

    Or will I have to do this manually with explode() to get the values left and right of the arithmetic operator?