Preg_replace简单的数学问题与解决方案? [英] Preg_replace simple math problem with solution?

查看:78
本文介绍了Preg_replace简单的数学问题与解决方案?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的字符串包含简单的数学问题1 + 10、2 + 2、5-3 ...我希望能够匹配这些数学问题并将其替换为解决方案.

I have strings that contain simple math problems 1+10, 2+2, 5-3... I'm wanting to be able to match these math problems and replace them with the solution.

这样:吉米(Jimmy)在星期五变成5 + 5.更改为:吉米(Jimmy)在星期五满10岁.

So that: Jimmy turns 5+5 on Friday. is changed to: Jimmy turns 10 on Friday.

在这一点上我不需要乘法或除法,因此我认为它相对简单,但是我没有经过PHP的经典训练.我认为我将需要一个正则表达式来解决这个问题,但是我从那里几乎迷失了.

I dont need multiplication or division at this point so i assume its relatively simple however im not classically trained in PHP. I assume i will need a REGEX to match the problem, but im pretty much lost from there.

1+10 becomes 11
2+2 becomes 4

推荐答案

只是评估"替换-但请注意,它是评估(

Just "eval" the replacement - but take care, it's eval (Demo):

$subject = 'Jimmy turns 5+5 on Friday, Martha 1+10 on Saturday and Petra is 2*2 today.';

$pattern = '~(\d+[*/+-]\d+)~e';
#                          ^^^ e = eval modifier

# Jimmy turns 10 on Friday, Martha 11 on Saturday and Petra is 4 today.
echo preg_replace($pattern, '$1', $subject);

这篇关于Preg_replace简单的数学问题与解决方案?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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