0

For example I have a statement:

$var = '2*2-3+8'; //variable type is string

How to make it to be equal 9 ?

2

4 Answers 4

7

From this page, a very awesome (simple) calculation validation regular expression, written by Richard van Velzen. Once you have that, and it matches, you can rest assured that you can use eval over the string. Always make sure the input is validated before using eval!

<?php
$regex = '{
    \A        # the absolute beginning of the string
    \h*        # optional horizontal whitespace
    (        # start of group 1 (this is called recursively)
    (?:
        \(        # literal (

        \h*
        [-+]?        # optionally prefixed by + or -
        \h*

        # A number
        (?: \d* \. \d+ | \d+ \. \d* | \d+) (?: [eE] [+-]? \d+ )?

        (?:
            \h*
            [-+*/]        # an operator
            \h*
            (?1)        # recursive call to the first pattern.
        )?

        \h*
        \)        # closing )

        |        # or: just one number

        \h*
        [-+]?
        \h*

        (?: \d* \. \d+ | \d+ \. \d* | \d+) (?: [eE] [+-]? \d+ )?
    )

    # and the rest, of course.
    (?:
        \h*
        [-+*/]
        \h*
        (?1)
    )?
    )
    \h*

    \z        # the absolute ending of the string.
}x';

$var = '2*2-3+8';

if( 0 !== preg_match( $regex, $var ) ) {
    $answer = eval( 'return ' . $var . ';' );
    echo $answer;
}
else {
    echo "Invalid calculation.";
}
Sign up to request clarification or add additional context in comments.

Comments

1

What you have to do is find or write a parser function that can properly read equations and actually calculate the outcome. In a lot of languages this can be implemented by use of a Stack, you should have to look at things like postfix and infix parsers and the like.

Hope this helps.

2 Comments

not to mention that there are tons of ready-made parsers right here in stackoverflow answers
Col. Shrapnel is probably right, I didn't have the time to look for ready-made parsers, good luck!
0
$string_with_expression = '2+2';
eval('$eval_result = ' . $string_with_expression)`;

$eval_result - is what you need.

Comments

-1

There is intval function

But you can't apply direct to $var

For parser Check this Answer

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.