Jump to content

[SOLVED] Reading a sum from a txt file and working it out?


Vivid Lust

Recommended Posts

Hey, i was wondering if you could work out a sum in a txt file.

 

Say in the text file the value was:

 

 (8+2)*4

 

How could i use php to read this and work it out??

 

My code so far is

<?php
$sumfile = "sum.txt";
$file = fopen( $sumfile, "w+");
$sum = fread($file, $filesize);
$answer = 
fwrite( $file, "<font color=red>.$answer</a>");
fclose( $file );
header('Location: calc2.php');
?>

 

Thanks!

Since there are no variables, I think it would be some pretty intensive testing with if statements.  You would have to baby step each character using substr and incrementing 1 within a loop.  Throughout that you will have to test for the possibilities of whether or not it is an integer(in which you will be working with), a nesting character ([ ] ( ) { }) or a mathematical sign( + - / * %).  That is probably the easy part.  To accurately calculate the values, you will have to have a quite complex set of logical determinations to properly put the characters into variables and execute the calculation in proper sequence.  Unless someone has an easier way, I would probably try to see if you can use an interface to input the numbers or something.  You might try posting on the Math Based Programming Sub Forum:

http://www.phpfreaks.com/forums/index.php/board,68.0.html

<?php
$file = file("file.txt"); //file only contains the equation (8+2)*4 and nothing else!
$zipped = implode('', $file);

function strtonum($str)
{
    $str = preg_replace('`([^+\-*=/\(\)\d\^<>&|\.]*)`','',$str);
    if(empty($str))$str = '0';
    else eval("\$str = $str;");
    return $str;
}

echo strtonum("$zipped"); // echos 40... the correct sum

?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.