开发者

Preg_replace simple math problem with solution?

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.

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

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 mu开发者_StackOverflow中文版ch 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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜