note 37134 added to function.eval
| From: | David at rn2 dot php dot net | Date: | Tue, 04 Nov 2003 16:17:32 +0000 |
| Subject: | note 37134 added to function.eval | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-59893@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:
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.
----
Manual Page -- http://www.php.net/manual/en/function.eval.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+37134
Delete -- http://master.php.net/manage/user-notes.php?action=delete+37134&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+37134&report=yes
Search -- http://master.php.net/manage/user-notes.php