Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- global $pre, $suff;
- $pre = "#(?<![0-9])([-+]?([0-9]*\.[0-9]+|[0-9]+))(([";
- $suff = "])([-+]?([0-9]*\.[0-9]+|[0-9]+)))+#";
- function replace_bracket($input) {
- global $pre,$suff;
- $operations = array("/", "*", "-", "+");
- $result = $input;
- if(is_array($input)) {
- $result = $input[1];
- }
- foreach($operations as $op) {
- $result = preg_replace_callback($pre.$op.$suff, 'replace_math' ,$result);
- }
- return $result;
- }
- function replace_math($matches) {
- if ($matches[4] == '-') {
- $vals = explode('!', preg_replace('/(--)*-(-?)/', '!$2', $matches[0]));
- }else {
- $vals = explode($matches[4], $matches[0]);
- }
- switch($matches[4]) {
- case '*':
- return array_product($vals);
- case '/':
- $result = array_shift($vals);
- foreach($vals as $val) {$result/=$val;}
- return $result;
- case '+':
- return array_sum($vals);
- case '-':
- return array_shift($vals)-array_sum($vals);
- }
- }
- $mathString = "(3+4-5.5*3)*-20/(5+81-3)-5+4*-3.141529*-10";
- $result = $mathString;
- while(strpos($result,"(")!== false) {
- $result = preg_replace_callback('/\\(([^()]*)\\)/', 'replace_bracket', $result);
- }
- $result = replace_bracket($result);
- eval('$phpResult = '.$mathString.';');
- echo $phpResult. " == ".$result;
Advertisement
Add Comment
Please, Sign In to add comment