Reputation: 59
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
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);
Upvotes: 2
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