php 正则表达式只允许小写字母
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14107331/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Regular expression to only allow lower-case letters
提问by John
Possible Duplicate:
Regular Expressions: low-caps, dots, zero spaces
可能的重复:
正则表达式:低大写、点、零空格
How could I change the regular expression below to only allow lower-case letters?
如何更改下面的正则表达式以只允许小写字母?
function valid_username($username, $minlength = 3, $maxlength = 30)
{
$username = trim($username);
if (empty($username))
{
return false; // it was empty
}
if (strlen($username) > $maxlength)
{
return false; // to long
}
if (strlen($username) < $minlength)
{
return false; //toshort
}
$result = ereg("^[A-Za-z0-9_\-]+$", $username); //only A-Z, a-z and 0-9 are allowed
if ($result)
{
return true; // ok no invalid chars
} else
{
return false; //invalid chars found
}
return false;
}
回答by Dave
You have both A-Z and a-z in your character class, just omit the A-Z to only allow for the a-z (lowercase) letters. I.e.
您的字符类中有 AZ 和 az,只需省略 AZ 以仅允许 az(小写)字母。IE
"^[a-z0-9_\-]+$"
回答by Sverri M. Olsen
You just remove the A-Zfrom the regular expression.
您只需A-Z从正则表达式中删除。
Also, since you are already using a regular expression you can just put everything into it, like this:
此外,由于您已经在使用正则表达式,因此您可以将所有内容放入其中,如下所示:
function valid_username($username, $minlength = 3, $maxlength = 30)
{
$regex = "/^[a-z0-9_\-]{{$minlength},{$maxlength}}$/";
return preg_match($regex, trim($username)) === 1;
}
It will make sure that the username is not empty, is of the permitted length, and that it only contains allowed characters.
它将确保用户名不为空,具有允许的长度,并且只包含允许的字符。
回答by Jordi Kroon
The function eregis deprecated. Use preg_match. Why don't you just use the function strtolower? preg_match('/^[a-z0-9]+$/', $nickname);
该功能ereg已弃用。使用 preg_match。你为什么不直接使用这个函数strtolower?preg_match('/^[a-z0-9]+$/', $nickname);
EDIT:
编辑:
preg_match('/^[a-z]+$/', $user);
preg_match('/^[az]+$/', $user);
回答by ROY Finley
The best option is a combination of Dave's and Jordi12100"s answer:
最好的选择是结合 Dave 和 Jordi12100 的回答:
Use pre_match()and drop out the A-Z
使用pre_match()和退出 AZ

