PHP正则表达式只检查输入中的第一个字符

时间:2014-04-20 17:49:44

标签: php regex

我正在为我正在做的网站制作登录系统。 我只有有限的使用正则表达式的经验,并且由于某种原因它不起作用。 有问题的代码是:

if (!(preg_match("/[A-Za-z0-9_ ]+/",$username)&&(strlen($username)>=4) && 
strlen($username)<=25))
{
      return 4;
}

长度检查正常,但字符检查没有。 它应该检查以确保$username仅包含字母,数字_和空格。 它似乎只检查第一个字符,然后,任何事情都会发生!

如果有人可以提供帮助,我们将不胜感激,谢谢!

2 个答案:

答案 0 :(得分:4)

尝试使用“排在第一位”^和“行尾”$修饰符

例如:

 preg_match("/^[A-Za-z0-9_ ]+$/",$username)

答案 1 :(得分:1)

您正在寻找以下正则表达式:

/^[a-z0-9_ ]+$/i

正则表达式

^             # the beginning of the string
 [a-z0-9_ ]+  # any character of: 'a' to 'z', '0' to '9', '_', ' ' (1 or more times)
$             # before an optional \n, and the end of the string