Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- $calc = array(
- '+' => 'bcadd',
- '-' => 'bcsub',
- '*' => 'bcmul'
- );
- $mathString = '5*19+45-6*7+21';
- $numbers = preg_split('/[\+\-*]+/', $mathString);
- $operators = preg_split('/[\d]+/', $mathString, -1, PREG_SPLIT_NO_EMPTY);
- $numOperators =count($operators);
- for ($i = 0; $i< $numOperators; $i++) {
- if ($operators[$i] == '*') {
- $numbers[$i] = call_user_func('bcmul', $numbers[$i], $numbers[$i+1]);
- $numbers[$i+1] = 0;
- $operators[$i] = '+';
- }
- }
- $sum = $numbers[0];
- for ($i = 0; $i< $numOperators; $i++) {
- $sum = call_user_func($calc[$operators[$i]], $sum, $numbers[$i+1]);
- }
- echo "Result: ".$sum;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement