简体   繁体   English

PHP-帮助正则表达式?

[英]PHP - Help with regex?

I wouldn't call myself a master regarding regex, i pretty much just know the basics. 我不会称自己是正则表达式的高手,我几乎只知道基本知识。 I've been playing around with it, but i can't seem to get the desired result. 我一直在玩,但似乎无法达到预期的效果。 So if someone would help me, i would really appreciate it! 因此,如果有人能帮助我,我将非常感激!

I'm trying to check wether unwanted words exist in a string. 我正在尝试检查字符串中是否存在不需要的单词。 I'm working on a math project, and i'm gonna be using eval() to calculate the string, so i need to make sure it's safe. 我正在做一个数学项目,并且我要使用eval()来计算字符串,所以我需要确保它是安全的。

The string may contain (just for example now, i'll add more functions later) the following words: (read the comments) 该字符串可能包含(例如,现在,我稍后将添加更多功能)以下单词:(阅读注释)

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. 我希望你至少可以给我一些提示。

Thanks in advance, -Anthony 预先感谢-安东尼

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. 我一直在寻找一种可以计算输入字符串的安全数学类/函数,但是我还没有找到。

Please do not use eval() for this. 请不要为此使用eval()。

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. 不要使用eval(尤其是在公式包含用户输入的情况下)或通过编写自己的公式解析器来重新发明轮子。

Take a look at the evalMath class on PHPClasses. 看一下PHPClasses上的evalMath类。 It should do everything that you want in a nice safe sandbox. 它应该在一个安全的沙盒中完成您想要的所有事情。

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. 当然,使用eval本质上是危险的,并且很难保证此正则表达式将以语法像PHP这样广泛的语言提供全面的保护。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM