note 37134 deleted from function.eval by danbrown

From: Date: Sun, 17 May 2009 20:01:24 +0000
Subject: note 37134 deleted from function.eval by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-155309@lists.php.net to get a copy of this message
Note Submitter: David Schumann ---- To evaluate math expressions (multiply, divide, addition, subtraction, percentages), use the following function, based on Taras Young's 'evalsum' function posted earlier: <?php function matheval($equation){ $equation = preg_replace("/[^0-9+\-.*\/()%]/","",$equation); $equation = preg_replace("/([+-])([0-9]+)(%)/","*(1\$1.\$2)",$equation); // you could use str_replace on this next line // if you really, really want to fine-tune this equation $equation = preg_replace("/([0-9]+)(%)/",".\$1",$equation); if ( $equation == "" ) { $return = 0; } else { eval("\$return=" . $equation . ";"); } return $return; } ?> You could easily extend this to include exponents, square roots, or really any other mathematical function. I use it in a 'price each' field on a purchase order form. The user can type in '$10.00-25%' and get 7.50 as the result.

« previous php.notes (#155309) next »