Preg_replace simple math problem with solution?

2019-08-06 23:47发布

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 much lost from there.

1+10 becomes 11
2+2 becomes 4

1条回答
等我变得足够好
2楼-- · 2019-08-07 00:44

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);
查看更多
登录 后发表回答