Basic Math solver from a string help!

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
walkekev
Forum Newbie
Posts: 4
Joined: Wed Mar 22, 2006 7:38 pm

Basic Math solver from a string help!

Post by walkekev »

I am writing a basic math solver that will follow order of operations. my problem comes in when numbers with numbers after the decimal come into play with multiplication and division. For example

Code: Select all

<?php

echo(solve("2/3*6"));
echo('<br>');
echo(solve(".5*10"));

function solve($temp){
	$z = false;
	while(!$z){
		$exp = explode('/', $temp, 2);
		if(count($exp) == 2){
			$part  = $exp[0];
			$part2 = $exp[1];
			$p1a = split('[*+-/]', $part);
			$count = count($p1a) - 1;
			$p1 = $p1a[$count];
			$p2a = split('[*+-/]', $part2);
			$p2 = $p2a[0];
			$p3 = $p1/$p2;
			$temp = str_replace("$p1/$p2",$p3,$temp);
			}
		else{
			$z = true;
			}
		}
	$z = false;
	while(!$z){
		$exp = explode('*', $temp, 2);
		if(count($exp) == 2){
			echo('Working the multiplecation<br>');
			$part  = $exp[0];
			$part2 = $exp[1];
			$p1a = split('[*+-/]', $part);
			$count = count($p1a) - 1;
			$p1 = $p1a[$count];
			$p2a = split('[*+-/]', $part2);
			$p2 = $p2a[0];
			$p3 = $p1*$p2;
			$temp = str_replace("$p1*$p2",$p3,$temp);
			}
		else{
			$z = true;
			}
		}
	$z = false;
	while(!$z){
		$exp = explode('-', $temp, 2);
		if(count($exp) == 2){
			$part  = $exp[0];
			$part2 = $exp[1];
			$p1a = split('[*+-/]', $part);
			$count = count($p1a) - 1;
			$p1 = $p1a[$count];
			$p2a = split('[*+-/]', $part2);
			$p2 = $p2a[0];
			$p3 = $p1-$p2;
			$temp = str_replace("$p1-$p2",$p3,$temp);
			}
		else{
			$z = true;
			}
		}
	$z = false;
	while(!$z){
		$exp = explode('+', $temp, 2);
		if(count($exp) == 2){
			$part  = $exp[0];
			$part2 = $exp[1];
			$p1a = split('[*+-/]', $part);
			$count = count($p1a) - 1;
			$p1 = $p1a[$count];
			$p2a = split('[*+-/]', $part2);
			$p2 = $p2a[0];
			$p3 = $p1+$p2;
			$temp = str_replace("$p1+$p2",$p3,$temp);
			}
		else{
			$z = true;
			}
		}
	return $temp;
	}
?>
results in

Code: Select all

0.6.66666666679
.50
please help! :(
walkekev
Forum Newbie
Posts: 4
Joined: Wed Mar 22, 2006 7:38 pm

Post by walkekev »

ok, I know what is causing it.

Code: Select all

<?php
echo(split('[*+-/]', '.5');
?>

results in

Code: Select all

5
why is it getting rid of the . before the 5??? please help me
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

- means the characters between the left and right of it (normally) .. don't use the ereg_ regular expressions...
Post Reply