you*_*les 3 php regex preg-match
我做了这个正则表达式:
^[a-zA-Z0-9_.-]*$
Run Code Online (Sandbox Code Playgroud)
支持:
letters [uppercase and lowercase]
numbers [from 0 to 9]
underscores [_]
dots [.]
hyphens [-]
Run Code Online (Sandbox Code Playgroud)
现在,我想添加以下内容:
spaces [ ]
comma [,]
exclamation mark [!]
parenthesis [()]
plus [+]
equal [=]
apostrophe [']
double quotation mark ["]
at [@]
dollar [$]
percent [%]
asterisk [*]
Run Code Online (Sandbox Code Playgroud)
例如,此代码仅接受上面的一些符号:
^[a-zA-Z0-9 _.,-!()+=“”„@"$#%*]*$
Run Code Online (Sandbox Code Playgroud)
返回:
警告:preg_match():编译失败:偏移量为16的字符类中的范围乱序
anu*_*ava 15
确保-在字符类的开头或结尾处输入连字符,否则需要对其进行转义.试试这个正则表达式:
^[a-zA-Z0-9 _.,!()+=`,"@$#%*-]*$
Run Code Online (Sandbox Code Playgroud)
还要注意,因为*它甚至会匹配一个空字符串.如果您不想匹配空字符串,请使用+:
^[a-zA-Z0-9 _.,!()+=`,"@$#%*-]+$
Run Code Online (Sandbox Code Playgroud)
或更好:
^[\w .,!()+=`,"@$#%*-]+$
Run Code Online (Sandbox Code Playgroud)
测试:
$text = "_.,!()+=,@$#%*-";
if(!preg_match('/\A[\w .,!()+=`,"@$#%*-]+\z/', $text)) {
echo "error.";
}
else {
echo "OK.";
}
Run Code Online (Sandbox Code Playgroud)
打印:
OK.
Run Code Online (Sandbox Code Playgroud)