PHP preg_match-仅允许字母数字字符串和-_个字符 [英] PHP preg_match - only allow alphanumeric strings and - _ characters
本文介绍了PHP preg_match-仅允许字母数字字符串和-_个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要使用正则表达式来检查字符串是否仅包含数字,字母,连字符或下划线
I need the regex to check if a string only contains numbers, letters, hyphens or underscore
$string1 = "This is a string*";
$string2 = "this_is-a-string";
if(preg_match('******', $string1){
echo "String 1 not acceptable acceptable";
// String2 acceptable
}
推荐答案
代码:
if(preg_match('/[^a-z_\-0-9]/i', $string))
{
echo "not valid string";
}
说明:
- [] =>字符类定义
- ^ =>否定课程
- a-z =>从'a'到'z'的字符
- _ =>下划线
- -=>连字符'-'(您需要对其进行转义)
- 0-9 =>数字(从零到九)
如果您不输入正则表达式末尾的"i"修饰符,则表示不区分大小写",您需要在执行A-Z之前在代码中添加大写字母
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
这篇关于PHP preg_match-仅允许字母数字字符串和-_个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文