Guest User

Rechenbeispiel mit Klammern

a guest
May 31st, 2011
167
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <?php
  2. global $pre, $suff;
  3. $pre = "#(?<![0-9])([-+]?([0-9]*\.[0-9]+|[0-9]+))(([";
  4. $suff = "])([-+]?([0-9]*\.[0-9]+|[0-9]+)))+#";
  5.  
  6. function replace_bracket($input) {
  7.     global $pre,$suff;
  8.     $operations = array("/", "*", "-", "+");
  9.     $result = $input;
  10.     if(is_array($input)) {
  11.         $result = $input[1];
  12.     }
  13.     foreach($operations as $op) {
  14.         $result = preg_replace_callback($pre.$op.$suff, 'replace_math' ,$result);
  15.     }
  16.     return $result;
  17. }
  18.  
  19. function replace_math($matches) {
  20.     if ($matches[4] == '-') {
  21.         $vals = explode('!', preg_replace('/(--)*-(-?)/', '!$2', $matches[0]));
  22.     }else {
  23.         $vals = explode($matches[4], $matches[0]);
  24.     }
  25.     switch($matches[4]) {
  26.         case '*':
  27.             return array_product($vals);
  28.         case '/':
  29.             $result = array_shift($vals);
  30.             foreach($vals as $val) {$result/=$val;}
  31.             return $result;
  32.         case '+':
  33.             return array_sum($vals);
  34.         case '-':
  35.             return array_shift($vals)-array_sum($vals);
  36.     }
  37. }
  38.  
  39. $mathString = "(3+4-5.5*3)*-20/(5+81-3)-5+4*-3.141529*-10";
  40. $result = $mathString;
  41. while(strpos($result,"(")!== false) {
  42.     $result = preg_replace_callback('/\\(([^()]*)\\)/', 'replace_bracket', $result);
  43. }
  44. $result = replace_bracket($result);
  45. eval('$phpResult = '.$mathString.';');
  46. echo $phpResult. " == ".$result;
RAW Paste Data