[英]Regular expression for allowed characters
i need to check, if the string in my PHP code contains only a specified list of characters. 我需要检查,如果我的PHP代码中的字符串仅包含指定的字符列表。 But as some of them might need scape, i just can't get it to work.
但是由于其中一些可能需要花scape,我只是无法使其发挥作用。 I have tried everything, but it just doesen't work...
我已经尝试了所有方法,但是却行不通...
The required validation is: 所需的验证是:
Basicaly, i want to check if there is an unknown ascii character (i don't know if there is a function to do that already). 基本上,我想检查是否有一个未知的ascii字符(我不知道是否已经有一个函数可以做到这一点)。
My code is like this now: 我的代码现在是这样的:
if(preg_match("/[A-Za-z0-9\.\#\-\+\*\\\/\=\_\%\$\(\)]/", $cmd) === false)
So, all of the chars are special? 那么,所有字符都是特殊的吗?
No, all of those characters are not special. 不,所有这些字符都不特殊。 If you're unsure, you can let PHP do the escaping for you with
preg_quote()
: 如果不确定,可以让PHP使用
preg_quote()
进行转义:
$regex = '/[A-Za-z0-9' . preg_quote( '.%^&()$#@!/-+/', '/') . ']+/';
if( !preg_match( $regex, $cmd))
Also, preg_match()
returns an int
, and you're doing ===
on a boolean, which will never hold true, since they will never be of the same type. 另外,
preg_match()
返回一个int
,并且您正在对布尔值执行===
,因为它们永远不会是同一类型,所以永远不会成立。 You can simply check for if( !preg_match())
. 您可以简单地检查
if( !preg_match())
。
if(preg_match("/[.%^&()$#@!/+-a-zA-Z\\d\\s]+/", $cmd) === false)
并且是否需要锚if(preg_match("/^[.%^&()$#@!/+-a-zA-Z\\d\\s]+$/", $cmd) === false)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.