Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- class Calc
- {
- public $result;
- public function __construct($string)
- {
- $this->parse($string);
- }
- protected function parse($string)
- {
- while (true) {
- preg_match('/\(([^()]*)\)/', $string, $matches);
- if (!count($matches)) {
- break;
- }
- $replace = $this->calculate($matches[1]);
- $string = str_replace($matches[0], $replace, $string);
- }
- $this->result = $this->calculate($string);
- }
- protected function calculate($string)
- {
- $operations = ['*' => 'mul', '/' => 'div'];
- foreach ($operations as $operation => $method) {
- while (true) {
- preg_match('/(-?\d+) \\' . $operation . ' (-?\d+)/', $string, $matches);
- if (!count($matches)) {
- break;
- }
- $string = $this->$method($string, $matches);
- }
- }
- while (true) {
- preg_match('/(-?\d+) (\+|-) (-?\d+)/', $string, $matches);
- if (!count($matches)) {
- break;
- }
- if ($matches[2] == '+') {
- $string = $this->sum($string, $matches);
- } else {
- $string = $this->sub($string, $matches);
- }
- }
- return $string;
- }
- protected function mul($string, $matches)
- {
- return str_replace($matches[0], $matches[1] * $matches[2], $string);
- }
- protected function div($string, $matches)
- {
- return str_replace($matches[0], $matches[1] / $matches[2], $string);
- }
- protected function sum($string, $matches)
- {
- return str_replace($matches[0], $matches[1] + $matches[3], $string);
- }
- protected function sub($string, $matches)
- {
- var_dump($matches);
- return str_replace($matches[0], $matches[1] - $matches[3], $string);
- }
- }
- $calc = new Calc('3 * 5 + 7 * 2');
- var_dump('3 * 5 + 7 * 2 = ' . $calc->result);
- $calc = new Calc('5 * (7 * (5 + 3) / 4 - 4)');
- var_dump('5 * (7 * (5 + 3) / 4 - 4) = ' . $calc->result);
- $calc = new Calc('(2 * (2 * 2 * (2 * 2)))');
- var_dump('(2 * (2 * 2 * (2 * 2))) = ' . $calc->result);
- $calc = new Calc('-5 + (3 * (-2 - 4))');
- var_dump('-5 + (3 * (-2 - 4)) = ' . $calc->result);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement