PHP - 正则表达式只允许字母和数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4345621/
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
PHP - regex to allow letters and numbers only
提问by Jason94
I have tried:
我试过了:
preg_match("/^[a-zA-Z0-9]", $value)
but im doing something wrong i guess.
但我猜我做错了什么。
回答by SW4
1. Use PHP's inbuilt ctype_alnum
1.使用PHP内置的ctype_alnum
You dont need to use a regex for this, PHP has an inbuilt function ctype_alnum
which will do this for you, and execute faster:
您不需要为此使用正则表达式,PHP 有一个内置函数ctype_alnum
可以为您执行此操作,并且执行速度更快:
<?php
$strings = array('AbCd1zyZ9', 'foo!#$bar');
foreach ($strings as $testcase) {
if (ctype_alnum($testcase)) {
echo "The string $testcase consists of all letters or digits.\n";
} else {
echo "The string $testcase does not consist of all letters or digits.\n";
}
}
?>
2. Alternatively, use a regex
2. 或者,使用正则表达式
If you desperately want to use a regex, you have a few options.
如果您非常想使用正则表达式,您有几个选择。
Firstly:
首先:
preg_match('/^[\w]+$/', $string);
\w
includes more than alphanumeric (it includes underscore), but includes all
of \d
.
\w
包括多个字母数字(包括下划线),但包括所有\d
.
Alternatively:
或者:
/^[a-zA-Z\d]+$/
Or even just:
或者甚至只是:
/^[^\W_]+$/
回答by Kendall Hopkins
You left off the /
(pattern delimiter) and $
(match end string).
您省略了/
(模式分隔符) 和$
(匹配结束字符串)。
preg_match("/^[a-zA-Z0-9]+$/", $value)
回答by KingCrunch
- Missing end anchor $
- Missing multiplier
- Missing end delimiter
- 缺少结束锚 $
- 缺少乘数
- 缺少结束分隔符
So it should fail anyway, but if it may work, it matches against just one digit at the beginning of the string.
所以无论如何它都应该失败,但如果它可以工作,它只会匹配字符串开头的一位数字。
/^[a-z0-9]+$/i
回答by Andrew
As the OP said that he wants letters and numbers ONLY (no underscore!), one more way to have this in phpregex is to use posix expressions:
正如 OP 所说,他只想要字母和数字(没有下划线!),在phpregex 中实现这一点的另一种方法是使用 posix 表达式:
/^[[:alnum:]]+$/
Note: This will not work in Java, JavaScript, Python, Ruby, .NET
注意:这不适用于 Java、JavaScript、Python、Ruby、.NET
回答by pooja
try this way .eregi("[^A-Za-z0-9.]", $value)
试试这种方式 .eregi("[^A-Za-z0-9.]", $value)