Reputation: 9
I'm trying to check wether unwanted words exist in a string. I'm working on a math project, and I'm going to be using eval()
to calculate the string, so I need to make sure it's safe.
The string may contain (potentially nested) PHP functions such as floor()
.
Considering floor()
, spaces or numbers are allowed between the () chars. If possible, I'd also like to allow other math functions inside, so it'd look like: floor( floor(8)*1 )
It may contain any digit, any math sign (+
, -
, *
, /
) and dots/commas (,
, .
) anywhere in the string
Just to be clear, here's another example: If a string like this is passed, I do not want it to pass:
9*9 + include('somefile') / floor(2) // Just a random example on something that's not allowed
Now that i think about it, it looks kind of complicated. I hope you can at least give me some hints.
Edit: This is a bit off-topic, but if you know a better way of calculating math functions, please suggest it. I've been looking for a safe math class/function that calculates an input string, but I haven't found one yet.
Upvotes: 0
Views: 157
Reputation: 1144
To rephrase your problem, you want to allow only a specific set of characters, plus certain predefined words. The alternation operator (pipe symbol) is your friend in this case:
([0-9\+\-\*\/\.\,\(\) ]|floor|ceiling|other|functions)*
Of course, using eval is inherently dangerous, and it is difficult to guarantee that this regex will offer full protection in a language with syntax as expansive as PHP.
Upvotes: 0
Reputation: 212522
Please do not use eval() for this.
My standard answer to this question whenever it crops up:
Don't use eval (especially if the formula contains user input) or reinvent the wheel by writing your own formula parser.
Take a look at the evalMath class on PHPClasses. It should do everything that you want in a nice safe sandbox.
Upvotes: 1