字母数字的正则表达式
我有这个 PHP 正则表达式:
$username = preg_replace('/[^a-z0-9]/i', '', $username);
它只允许 AZ
和 0-9
。如何同时允许 .
、-
和 _
?
I've this PHP regular expression:
$username = preg_replace('/[^a-z0-9]/i', '', $username);
It allows only A-Z
and 0-9
. How can I allow .
, -
and _
as well?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
您可以使用以下正则表达式:
匹配不区分大小写。你可以
删除它并使用:
/[^a-zA-Z0-9._-]/
一边,所以我们把它放在最后,这样
它按字面意思处理。您还可以
执行:
/[^a-z0-9.\-_]/
我们在哪里转义连字符
char 因此将按字面意思处理
并且不需要逃避。
You can use the following regex:
matching case-insensitive. You can
drop it and use:
/[^a-zA-Z0-9._-]/
sided so we put it at the end so that
its treated literally. You can also
do:
/[^a-z0-9.\-_]/
where we areescaping the hyphen
char hence will be treated literally
and need not be escaped.
很简单,只需将这些字符也添加到正则表达式中即可
。需要转义,因为它是“matchall”字符, - 放在最后,因为否则它将用于定义范围(我们当然可以转义它)。
Easy, just add those characters to the regular expression as well
The . needs to be escaped because its the 'matchall' character, the - goes in the end because otherwise it would be used to define a range (we could ofcourse have just escaped it).
删除不 (
[^]
) 组中字符之一的任何内容。请注意,hypern 是最后一个,因此它失去了其特殊含义。Removes anything that isn't (
[^]
) one of the characters on the group. Note the hypern is the last one there, so it loses its special meaning.如果您确切知道需要匹配什么,只需在字符组中指定它即可。破折号必须位于最开始或最后。
If you know exactly what you need to match, just specify it in a character group. The dash either needs to be at the very start or very end.
您当前的代码实际上允许
AZ
和az
-i
标志将您的正则表达式标记为不区分大小写。Your current code actually does allow both
A-Z
anda-z
- thei
flag marks your regular expression as case-insensitive.尝试
Try