Preg_match 不工作

Preg_match isn't working

我有这个 PHP preg_match 代码应该只允许 a-z(大写和小写)0-9 和下划线

但是当我尝试使用用户名 "Rizon" 注册时,它说: 只允许使用有效字符。

代码如下:

if (!preg_match("[a-zA-Z0-9]_",$_POST['username'])) {
$_SESSION['error']['username'] = "Only valid characters are allowed."; 
}

如何修复 preg_match 以便它允许用户名 "Rizon" 和大写 and/or 小写字母 and/or 数字 and/or 下划线的用户名?

试试这个

!preg_match("/[a-zA-Z0-9_]+/",$_POST['username']);

!preg_match("/[a-z0-9_]+/i",$_POST['username']);

首先,您缺少正则表达式的分隔符。您可以使用 /# 或任何其他 the available ones.
接下来,您已经声明要再次匹配的模式,它将转换为 "match a single alphanumeric symbol followed by underscore".
所以正如已经建议的那样使用

[a-zA-Z0-9_]+

改为正则表达式并使用模式定界符

preg_match('/[a-zA-Z0-9_]+/',$_POST['username'])

您也可以使用 modifier i 不区分大小写

preg_match('/[a-z0-9_]+/i',$_POST['username'])

这应该可以解决问题(您还需要检查用户名 只有 包含您的模式)

 if (!preg_match("/^[a-zA-Z0-9_]+$/",$_POST['username']))

如果不添加 ^(开始匹配)和 $(结束匹配),您的正则表达式将仅在包含模式时验证。

我认为这将是最简单的正则表达式。

if (!preg_match("~^\w+$~",$_POST['username'])) {
     $_SESSION['error']['username'] = "Only valid characters are allowed."; 
}

演示:https://regex101.com/r/rG3sJ3/1

\w 是任意字符 a-z、A-Z、0-9 和下划线。 +是一个或多个字符。

^是字符串的开始,$是结束。检查 regex101 link 进行测试和更详细的描述。

链接:

https://docs.oracle.com/javase/tutorial/essential/regex/pre_char_classes.html
https://docs.oracle.com/javase/tutorial/essential/regex/quant.html
https://docs.oracle.com/javase/tutorial/essential/regex/bounds.html

想想你可能想做的事:

if (preg_match("/\W/",$_POST['username'])) { // check for non-word chars
  $_SESSION['error']['username'] = "Only valid characters are allowed."; 
}

并单独验证长度:

if (!preg_match("/^.{6,8}$/",$_POST['username'])) { // check for length
  $_SESSION['error']['username'] = "6 to 8 letters please"; 
}