计算字符串中的总和 [英] Calculate a sum in a string

查看:179
本文介绍了计算字符串中的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的字符串:$string = "a + b + c";.现在,我想将字符串计算为总和.

I have string like this: $string = "a + b + c";. Now I would like to calculate the string as sum.

例如:

$a = 10;
$b = 10;
$c = 10;
$string = "a + b + c";

echo "Result is ".$string;
output-> Result is 30

$string = "a + b * c";

echo "Result is ".$string;
output-> Result is 110


预先感谢


Thanks in advance

推荐答案

字符串中的变量缺少美元符号.我为您编写并测试了一个脚本,该脚本将这些符号添加到变量中,然后使用功能eval()将字符串解析为PHP代码.

The variables in your string are missing the dollar signs. I wrote and tested a script for you that adds these signs to the variables and then parses the string as PHP code using the function eval().

$a = 10;
$b = 10;
$c = 10;
$string = "a + b + c";

$result = eval('return ' . preg_replace('/([a-zA-Z0-9])+/', '\$$1', $string) . ';');
echo $result;

这将输出30.

这篇关于计算字符串中的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆