user3472449
user3472449

Reputation: 59

Add numbers in a string using PHP stored in MySQL DB

I have a string save in mysql database like this:

"This is the total 98+84+67"

And I want the string to look like this when I display in my page using php:

"This is the total 249"

Is this possible without adding first the numbers before inserting in the database. Only add when I display the string to my site?

Please help!

Upvotes: 3

Views: 72

Answers (2)

FuzzyTree
FuzzyTree

Reputation: 32392

$string = "This is the total 98+84+67 of the numbers 98, 84 and 67 if we add.";
preg_match("/[\d]+\+[\d+]+/",$string,$matches);
$numbers = explode("+",$matches[0]);
$sum = array_sum($numbers);
print preg_replace("/[\d]+\+[\d+]+/",$sum,$string);

Demo

Upvotes: 2

Khalid
Khalid

Reputation: 4808

This code may help you, you should be sure that the expression in the end doesn't have any space

<?php
    $str = "This is the total 98+84+67";
    function calculate($str)
    {
        $exp = preg_replace('/[^0-9+]+/', "", $str);
        eval("\$result = " . $exp . ";");
        $str = str_replace($exp, $result, $str);
        return $str;
    }
    echo calculate($str);
?>

Upvotes: 0

Related Questions