用于验证字母数字字符串的 php 代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15920360/
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 code to validate alphanumeric string
提问by jayant kumar
I want to validate alphanumeric string in form text box in php. It can contain numbers and special characters like '.' and '-' but the string should not contain only numbers and special characters. Please help with the code.
我想验证 php 表单文本框中的字母数字字符串。它可以包含数字和特殊字符,如“.” 和 '-' 但字符串不应只包含数字和特殊字符。请帮忙看代码。
回答by Ravinder Payal
回答by Sankar V
Try this
尝试这个
// Validate alphanumeric
if (preg_match('/^[a-zA-Z]+[a-zA-Z0-9._]+$/', $input)) {
// Valid
} else {
// Invalid
}
回答by Navneet Soni
Code:
代码:
if(preg_match('/[^a-z_\-0-9]/i', $string))
{
echo "not valid string";
}
if(preg_match('/[^a-z_\-0-9]/i', $string))
{
echo "not valid string";
}
Explanation:
解释:
- [] => character class definition
- ^ => negate the class
- a-z => chars from 'a' to 'z'
- _ => underscore
- - => hyphen '-' (You need to escape it)
- 0-9 => numbers (from zero to nine)
- [] => 字符类定义
- ^ => 否定类
- az => 从 'a' 到 'z' 的字符
- _ => 下划线
- - => 连字符“-”(你需要转义它)
- 0-9 => 数字(从零到九)
The 'i' modifier at the end of the regex is for 'case-insensitive' if you don't put that you will need to add the upper case characters in the code before by doing A-Z
正则表达式末尾的“i”修饰符用于“不区分大小写”,如果您不添加,则需要在执行 AZ 之前在代码中添加大写字符
回答by rinchik
I'm sort of new to regex, but I would do it this way:
我对正则表达式有点陌生,但我会这样做:
preg_match('/^[\w.-]+$/', input)