Jump to content

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


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

?>

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.