-1

I have the following code:

 <!DOCTYPE html>
<html>
<head>
<title>Simple Calculator</title>
<h2>Simple Calculator</h2>
</head>
<body>
<?php
if(isset($_GET["number1"]) and isset($_GET["number2"]))
{
    if(!empty($_GET["number1"]) and !empty($_GET["number2"]))
    {

        global $n1;
        global $n2;

        $n1=$_GET["number1"];
        $n2=$_GET["number2"];

        $check_number1=@ereg("^[0-9]+$",$n1);
        $check_number2=@ereg("^[0-9]+$",$n2);
        if($check_number1==true and $check_number2==true)
        {
            function plus($n1,$n2)
            {       
            return $total=$n1+$n2;
            }

            echo plus($n1,$n2);
        }
        else
        {
        echo "error !";
        }
    }
    else
    {
    echo "input two numbers";
    }
}
?>


<form action="#" method="GET">
number 1 <input type="text" name="number1"><br>
number 2 <input type="text" name="number2"><br>
<input type="submit" value="compute">
</form>
</body>
</html>

How do I make PHP accept long match strings. For example, if I type 1+5 in the first field and 3+1 in the second field, I would like it to output 10. Or if I do 1 in the 1st field and 3+2 in the second field, it should output 6.

Mike
  • 23,542
  • 14
  • 76
  • 87
  • 6
    Why are you still using the deprecated ereg* functions? – Mark Baker Aug 01 '13 at 17:07
  • Oh my... so much wrong in so little code. Are you sure you don't want to throw a few `mysql_query` in there too? – Mike Aug 01 '13 at 17:19
  • possible duplicate of [how to evaluate formula passed as string in php?](http://stackoverflow.com/questions/1015242/how-to-evaluate-formula-passed-as-string-in-php) – Mike Aug 01 '13 at 17:21

1 Answers1

0

You could use the function eval, but this is very dangerous !

This class might help you : http://www.phpclasses.org/browse/package/2695.html

  • This class can be used to safely evaluate mathematical expressions.
  • The class can take an expression in a text string and evaluate it by replacing values of variables and calculating the results of mathematical functions and operations.
  • It supports implicit multiplication, multivariable functions and nested functions.
  • It can be used to evaluate expressions from untrusted sources. It provides robust error checking and only evaluates a limited set of functions.
  • It could be used to generate graphs from expressions of formulae.
Dawlys
  • 188
  • 6
  • You're just copying and pasting your answer from an [existing question](http://stackoverflow.com/questions/1015242). That's why I downvoted it. – Mike Aug 01 '13 at 17:22
  • The point is not whether it works or not. If there is already an existing question asking exactly the same thing, the best thing to do is to flag that question as being a duplicate of the other one, not just copying and pasting an existing answer as if it was your own and also creating duplicate content on the site. – Mike Aug 01 '13 at 17:26