How can I create an input text area, where someone can type in a string to calculate, such as:
code*9/6 (outputs 3)[/code]
I can't seem to get PHP to do that. Any ideas?
try using eval()
$string = "(1+1)*9/6";
echo eval($string);
I've tried using eval(), and it still just outputs whatever was inputted.
ok yeah i get an error too. i didnt test it.. ive tried a few things and cant get anything to work 🙁
Use
eval("return \$string;")
But like I said, it will only return whatever it was given.
I had already tried searching for a PHP calculator like this, but I couldn't find one. I don't believe it's not possible - it must be, but how? 😕
Originally posted by Gary W Use eval("return \$string;") But like I said, it will only return whatever it was given. I had already tried searching for a PHP calculator like this, but I couldn't find one. I don't believe it's not possible - it must be, but how? 😕 [/B]
Originally posted by Gary W Use
I had already tried searching for a PHP calculator like this, but I couldn't find one. I don't believe it's not possible - it must be, but how? 😕 [/B]
Of course it is possible, everything is possible in PHP! 🙂
Try this
<? $string = "(1+1)*2"; $s = "\$i = $string"; echo eval( "$s;return \$i;" ); ?>
HalfaBee
sure the last example works, but try doing that from POSTed data in a form.. it then fails.
Works fine! Try this.
<? $string = $_POST['string']; echo eval( "\$i = $string;return \$i;" ); ?> <FORM method=post > <input name=string > <input type=submit > </FORM>
echo eval ( "return $string" );
works just as well.
My final result:
http://personal.torontoview.com/calculate.php
And oh, the code for displaying the calculation result is the following:
if ($_POST['calculate']) { $string=$_POST['string']; print "<b>Result:</b> ".eval("return $string;"); }
🙂
You should do some checking to secure your input.
if( !preg_match( "/[(*-+0-9).\/]+/" ,$string ) ) echo 'No way am I doing that'; else echo eval( "return $string;" );
What would happen if I typed in unlink( ".") ?
It wouldn't work 😉
what about unlink(script.php)?
As I said, it won't work.
Ohh. The links not there! I wonder why? 🙂
Originally posted by HalfaBee Ohh. The links not there! I wonder why? 🙂
Because it's here now:
http://personal.torontoview.com/temp/calculate.php 😃