Home > Backend Development > PHP Tutorial > How to Safely Evaluate Mathematical Expressions from Strings in PHP?

How to Safely Evaluate Mathematical Expressions from Strings in PHP?

Mary-Kate Olsen
Release: 2024-12-27 22:44:17
Original
710 people have browsed it

How to Safely Evaluate Mathematical Expressions from Strings in PHP?

Evaluating Mathematical Expressions from Strings Using Eval

Issue:

When attempting to evaluate a mathematical expression stored in a string using eval(), a "Parse error" occurs, indicating an unexpected end of input.

Solution:

While it's generally not recommended to use eval() for this purpose due to security concerns, the following code modification resolves the issue:

$ma = "2+10";
$p = eval('return ' . $ma . ';');
print $p;
Copy after login

By explicitly returning the result within an eval() function, the code expects a complete line of code.

Alternative Solution:

A more secure and efficient solution is to use a tokenizer/parser to handle mathematical expressions. Here's a simple regex-based example:

$ma = "2+10";

if (preg_match('/(\d+)(?:\s*)([\+\-\*\/])(?:\s*)(\d+)/', $ma, $matches) !== FALSE) {
    $operator = $matches[2];

    switch ($operator) {
        case '+':
            $p = $matches[1] + $matches[3];
            break;
        case '-':
            $p = $matches[1] - $matches[3];
            break;
        case '*':
            $p = $matches[1] * $matches[3];
            break;
        case '/':
            $p = $matches[1] / $matches[3];
            break;
    }

    echo $p;
}
Copy after login

The above is the detailed content of How to Safely Evaluate Mathematical Expressions from Strings in PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template