Ryan Cooper
Ryan Cooper

Reputation: 703

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

1+10 becomes 11
2+2 becomes 4

Upvotes: 1

Views: 659

Answers (1)

hakre
hakre

Reputation: 198217

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);

Upvotes: 3

Related Questions