# Einfache Rechenoperationen

a guest
May 31st, 2011
142
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. <?php
2.
3. \$mathString = "-5.5*3*-20/5+81-3-5+4*-3.141529*-10";
4.
5. function replace_math(\$matches) {
6.     if (\$matches[4] == '-') {
7.         \$vals = explode('!', preg_replace('/(--)*-(-?)/', '!\$2', \$matches[0]));
8.     }else {
9.         \$vals = explode(\$matches[4], \$matches[0]);
10.     }
11.     switch(\$matches[4]) {
12.         case '*':
13.             return array_product(\$vals);
14.         case '/':
15.             \$result = array_shift(\$vals);
16.             foreach(\$vals as \$val) {\$result/=\$val;}
17.             return \$result;
18.         case '+':
19.             return array_sum(\$vals);
20.         case '-':
21.             return array_shift(\$vals)-array_sum(\$vals);
22.     }
23. }
24. \$result = preg_replace_callback("#(?<![0-9])([-+]?([0-9]*\.[0-9]+|[0-9]+))(([/])([-+]?([0-9]*\.[0-9]+|[0-9]+)))+#", 'replace_math' ,\$mathString);
25. \$result = preg_replace_callback("#(?<![0-9])([-+]?([0-9]*\.[0-9]+|[0-9]+))(([*])([-+]?([0-9]*\.[0-9]+|[0-9]+)))+#", 'replace_math' ,\$result);
26. \$result = preg_replace_callback("#(?<![0-9])([-+]?([0-9]*\.[0-9+]|[0-9]+))(([-])([-+]?([0-9]*\.[0-9]+|[0-9]+)))+#", 'replace_math' ,\$result);
27. \$result = preg_replace_callback("#(?<![0-9])([-+]?([0-9]*\.[0-9]+|[0-9]+))(([+])([-+]?([0-9]*\.[0-9]+|[0-9]+)))+#", 'replace_math' ,\$result);
28.
29. eval('\$phpResult = '.\$mathString.';');
30. echo \$phpResult. " == ".\$result;
RAW Paste Data