Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- $mathString = "-5.5*3*-20/5+81-3-5+4*-3.141529*-10";
- 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);
- }
- }
- $result = preg_replace_callback("#(?<![0-9])([-+]?([0-9]*\.[0-9]+|[0-9]+))(([/])([-+]?([0-9]*\.[0-9]+|[0-9]+)))+#", 'replace_math' ,$mathString);
- $result = preg_replace_callback("#(?<![0-9])([-+]?([0-9]*\.[0-9]+|[0-9]+))(([*])([-+]?([0-9]*\.[0-9]+|[0-9]+)))+#", 'replace_math' ,$result);
- $result = preg_replace_callback("#(?<![0-9])([-+]?([0-9]*\.[0-9+]|[0-9]+))(([-])([-+]?([0-9]*\.[0-9]+|[0-9]+)))+#", 'replace_math' ,$result);
- $result = preg_replace_callback("#(?<![0-9])([-+]?([0-9]*\.[0-9]+|[0-9]+))(([+])([-+]?([0-9]*\.[0-9]+|[0-9]+)))+#", 'replace_math' ,$result);
- eval('$phpResult = '.$mathString.';');
- echo $phpResult. " == ".$result;
Advertisement
Add Comment
Please, Sign In to add comment