Page 1 of 1

Basic Math solver from a string help!

Posted: Wed Mar 22, 2006 7:57 pm
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! :(

Posted: Wed Mar 22, 2006 8:33 pm
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

Posted: Wed Mar 22, 2006 8:48 pm
by feyd
- means the characters between the left and right of it (normally) .. don't use the ereg_ regular expressions...