views:

35

answers:

2

I'm attempting to make a function in PHP that will evaluate a mathematical expression -- including functions such as sin, cos, etc. My approach is to delete all characters in the phrase that are not numbers, mathematical operators, or mathematical functions and then use that string in an eval(). The problem is that I don't know enough about regular expressions to negate both characters and phrases in the same expression.

So far, this is what I've got:

$input = preg_replace("/[^0-9+\-.*\/()sincota]/", "", $input);

Obviously, the characters for sin, cos, and tan can be used in any order in the input expression (rather than only allowing the phrases sin, cos, and tan). If I further expand this function to include even more characters and functions, that presents an even bigger security risk as a malicious user would be able to execute just about any PHP command through clever interaction with the app.

Can anyone tell me how to fix my regex and eliminate this problem?

A: 

You could try this :

preg_replace("/(sin|cos|tan)?[^0-9+\\.*\/()-]/", "$1", $input);

code on ideone.com

But if you're trying to parse an expression to evaluate it, I suggest you to parse it and not simply pass it through a regular expression pattern.

Colin Hebert
+1  A: 

I'm attempting to make a function in PHP that will evaluate a mathematical expression -- including functions such as sin, cos, etc

Might I suggest taking advantage of the years of work that has been put into PHPExcel, which includes a formula parser already.

It includes cos, sin and hundreds of others.

Otherwise, rather than negating, you can look for positive matches:

$matches = array();
preg_match_all("#([0-9,/\*()+\s\.-]|sin|cos)+#", 'sin(12) + cos(13.5/2) evddal * (4-1)', $matches);
echo implode('', $matches[0]);

/* output:
sin(12) + cos(13.5/2) * (4-1) 
*/
webbiedave