PHP - parse mathematical equations inside strings

I'm struggling to find a better way to do this. In principle, I was provided with lines similar to this, with the task of printing a line with the analyzed mathematics.

Jack has a probability of [0.8 * 100]% to pass the test. Katie has a chance of [(0.25 + 0.1) * 100]%.

Mathematical equations are always enclosed in square brackets. Why I deal with lines like this is a long story, but I am very grateful for the help!

+5
source share
4 answers
preg_match_all('/\[(.*?)\]/', $string, $out);
foreach ($out[1] as $k => $v)
{
    eval("\$result = $v;");
    $string = str_replace($out[0][$k], $result, $string);
}

This code is very dangerous if the lines are user inputs, as it allows any arbitrary code to be executed.

+2
source

PHP. - .


, , . , .


eval. , , . eval docs . :

: , eval - , . , .

<?php

$test = '2+3*pi';

// Remove whitespaces
$test = preg_replace('/\s+/', '', $test);

$number = '(?:\d+(?:[,.]\d+)?|pi|π)'; // What is a number
$functions = '(?:sinh?|cosh?|tanh?|abs|acosh?|asinh?|atanh?|exp|log10|deg2rad|rad2deg|sqrt|ceil|floor|round)'; // Allowed PHP functions
$operators = '[+\/*\^%-]'; // Allowed math operators
$regexp = '/^(('.$number.'|'.$functions.'\s*\((?1)+\)|\((?1)+\))(?:'.$operators.'(?2))?)+$/'; // Final regexp, heavily using recursive patterns

if (preg_match($regexp, $q))
{
    $test = preg_replace('!pi|π!', 'pi()', $test); // Replace pi with pi function
    eval('$result = '.$test.';');
}
else
{
    $result = false;
}

?>
+3

eval PHP doc.

<?php
function calc($equation)
{
    // Remove whitespaces
    $equation = preg_replace('/\s+/', '', $equation);
    echo "$equation\n";

    $number = '((?:0|[1-9]\d*)(?:\.\d*)?(?:[eE][+\-]?\d+)?|pi|π)'; // What is a number

    $functions = '(?:sinh?|cosh?|tanh?|acosh?|asinh?|atanh?|exp|log(10)?|deg2rad|rad2deg|sqrt|pow|abs|intval|ceil|floor|round|(mt_)?rand|gmp_fact)'; // Allowed PHP functions
    $operators = '[\/*\^\+-,]'; // Allowed math operators
    $regexp = '/^([+-]?('.$number.'|'.$functions.'\s*\((?1)+\)|\((?1)+\))(?:'.$operators.'(?1))?)+$/'; // Final regexp, heavily using recursive patterns

    if (preg_match($regexp, $equation))
    {
        $equation = preg_replace('!pi|π!', 'pi()', $equation); // Replace pi with pi function
        echo "$equation\n";
        eval('$result = '.$equation.';');
    }
    else
    {
        $result = false;
    }
    return $result;
}
?>
0

, .... .

. php , . explode() str_split().

, : http://www.w3schools.com/php/php_ref_string.asp

.

-2
source

All Articles