1

So I have formula as string

$comm = "(a x 5% - 2%)";

I want it to be $comm = $a * 5/100 * (1-2/100);

How can I do this in php?

1
  • 3
    Probably, you'll need to write parser. Commented Feb 21, 2013 at 10:15

4 Answers 4

3

Take a look at

http://www.phpclasses.org/package/2695-PHP-Safely-evaluate-mathematical-expressions.html

Which can evaluate Math Code

 // instantiate a new EvalMath
  $m = new EvalMath;
  $m->suppress_errors = true;
 // set the value of x
  $m->evaluate('x = 3');
   var_dump($m->evaluate('y = (x > 5)'));

Found at: Process mathematical equations in php

Sign up to request clarification or add additional context in comments.

2 Comments

hi Duk i am getting an error Exception: Class 'EvalMath' not found how can i use this classs
Good one without reinventing the wheel!
3

To do this the right way, reliably and safely, from scratch, you will need to perform:

  1. Lexical analysis, this involves pattern matching the input with tokens:

    (a x 5% - 2%)
    

    would become something like the following chain of tokens:

    openparen variable multiply integer percent minus integer percent closeparen
    
  2. Syntax analysis, this involves taking those tokens and defining the relationships between them, something like this, matching up the patterns of tokens:

    statement = operand operator statement
    
  3. Then you will need to parse the resulting syntax tree so that you can run it and produce the answer.

It won't ever look as simple as $comm = $a * 5/100 - 2/100; but it will result in the same conclusion.

Someone somewhere has already likely had a go at this problem, here's two I found after a brief Google search: PHP Maths Expression Parser, And another.

These SO questions are similar as well Smart design of a math parser?, Process mathematical equations in php

Comments

1

It just trying, but maybe good start.

$somm = 0;
$a = 30;

$str = "(a x 5% - 2%)";

$pt1 = "/x/i";
$str = preg_replace($pt1, "*", $str);

$pt2 = "/([a-z])+/i";
$str = preg_replace($pt2, "\$$0", $str);

$pt3 = "/([0-9])+%/";
$str = preg_replace($pt3, "($0/100)", $str);

$pt4 = "/%/";
$str = preg_replace($pt4, "", $str);

$e = "\$comm = $str;";
eval($e);
echo $e . "<br>";
echo $comm; 

Comments

0

Solved!!

<?php 
    function evalmath($equation)
    {
        $result = 0;
        // sanitize imput
        $equation = preg_replace("/[^a-z0-9+\-.*\/()%]/","",$equation);
        // convert alphabet to $variabel 
        $equation = preg_replace("/([a-z])+/i", "\$$0", $equation); 
        // convert percentages to decimal
        $equation = preg_replace("/([+-])([0-9]{1})(%)/","*(1\$1.0\$2)",$equation);
        $equation = preg_replace("/([+-])([0-9]+)(%)/","*(1\$1.\$2)",$equation);
        $equation = preg_replace("/([0-9]{1})(%)/",".0\$1",$equation);
        $equation = preg_replace("/([0-9]+)(%)/",".\$1",$equation);
        /*if ( $equation != "" ){
            $result = @eval("return " . $equation . ";" );
        }
        if ($result == null) {
            throw new Exception("Unable to calculate equation");
        }
        return $result;*/
        return $equation;
    }
    $total = 18000;
    $equation =  evalmath('total-(230000*5%-2%+3000*2*1)');
    if ( $equation != "" ){

        $result = @eval("return " . $equation . ";" );
    }
    if ($result == null) {

        throw new Exception("Unable to calculate equation");
    }
    echo $result;
?>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.