2

After a lot of operations I've got some like:

$exr = "2+3/1.5";

How I can get result of this expression? Like this:

$result = (floatval)$exr; // show: 4

Of course it doesn't work. I've got only 2, first symbol. Any easy way to solve this?

6 Answers 6

3

You can use the PHP eval function like this:

$exr = '2+3/1.5';
eval('$result = ' . $exr . ';');
var_dump($result);
// float(4)

Read this note carefully:

Caution: The eval() language construct is very dangerous because it allows execution of arbitrary PHP code. Its use thus is discouraged. If you have carefully verified that there is no other option than to use this construct, pay special attention not to pass any user provided data into it without properly validating it beforehand.

Sign up to request clarification or add additional context in comments.

2 Comments

Here any way for make regex which only work with math functions and operations? Like: +; -; /; *; sqrt; pow; cos; sin; etc?
How come you are discouraging the use of eval and giving the same solution?
2

Eval is EVIL

I dont know why every answer here is telling you to do this? But avoid using this.

Here is very good function that can do the same without the eval() Source

function calculate_string( $mathString )    {
    $mathString = trim($mathString);     // trim white spaces
    $mathString = ereg_replace ('[^0-9\+-\*\/\(\) ]', '', $mathString);    // remove any non-numbers chars; exception for math operators
 
    $compute = create_function("", "return (" . $mathString . ");" );
    return 0 + $compute();
}

Use it as

$exr = '2+3/1.5';
echo calculate_string($exr);

1 Comment

Good idea! But need to correct regex a little bit. Cause in math available also cos, sin, pow, etc.
1

You could use the eval function:

$result = eval($exr); // show: 4

2 Comments

Thanks a lot. I can't understand how "googling" with that question?! Bad English :)
You could try this query or see Salman comment's on the accepted answer :)
1

Try:

$exr = "2+3/1.5";
echo eval("return $exr;"); //shows 4

Comments

0

You could use eval.

$result = eval($exr);

Comments

0

The easiest way would be to just run it through eval(), but that is very insecure. For security I'd recommend to filter certain characters, like a-z and special chars like ";:'.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.