note 37134 modified in function.eval by danbrown

From: Date: Tue, 25 Nov 2008 16:10:28 +0000
Subject: note 37134 modified in function.eval by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-146951@lists.php.net to get a copy of this message
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. --was-- To evaluate math expressions (multiply, divide, addition, subtraction, percentages), use the following function, based on Taras Young's 'evalsum' function posted earlier: 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. http://php.net/manual/en/function.eval.php

« previous php.notes (#146951) next »