Question

I mean convert this: '1+1' to this: 1+1.

I´ve found this answer, that says that you can perform math operations on strings, like this:

$num = "10" + 1;

But it´s not the same here, because the math operator is inside the string.

Was it helpful?

Solution

If your equations stay pretty simple you can make a function similar to the following:

function calcString($str)
{
    $patten = '/[\*\/\+-]/';
    preg_match($patten,$str, $operator);
    $arr = preg_split($patten,$str);

    switch($operator[0]){
    case '-':
        return $arr[0] - $arr[1];
    case '+':
        return $arr[0] + $arr[1];
    case '*':
        return $arr[0] * $arr[1];
    case '/':
        return $arr[0] / $arr[1];
    }
}

$num = "10+2";
echo calcString($num); // Output = 12
// Or
$num = "10-2";
echo calcString($num); // Output = 8
// Or
$num = "10*2";
echo calcString($num); // Output = 20
// Or
$num = "10/2";
echo calcString($num); // Output = 5

Of course you could put the function is some kind of helper class.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top