[英]PHP preg_match - only allow alphanumeric strings and - _ characters
我需要正则表达式来检查字符串是否只包含数字,字母,连字符或下划线
$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";
}
说明:
正则表达式末尾的'i'修饰符用于'不区分大小写',如果你没有说你需要在代码中添加大写字符之前做AZ
if(!preg_match('/^[\w-]+$/', $string1)) {
echo "String 1 not acceptable acceptable";
// String2 acceptable
}
这是UTF-8世界接受的答案的一个等价物。
if (!preg_match('/^[\p{L}\p{N}_-]+$/u', $string)){
//Disallowed Character In $string
}
说明:
请注意,如果连字符是类定义中的最后一个字符,则不需要对其进行转义 。 如果破折号出现在类定义的其他位置,则需要对其进行转义 ,因为它将被视为范围字符而不是连字符。
这是一个使用str_word_count()的时髦非正则表达式方法:
if($string===str_word_count($string,1,'-_0...9')[0]){
// ^^^^^^^--- characters to allow, see documentation
echo "pass";
}else{
echo "fail";
}
查看演示链接 ,其中显示了不同输入如何产生不同的输出数组。
为什么要使用正则表达式? PHP有一些内置的功能来做到这一点
<?php
$valid_symbols = array('-', '_');
$string1 = "This is a string*";
$string2 = "this_is-a-string";
if(preg_match('/\s/',$string1) || !ctype_alnum(str_replace($valid_symbols, '', $string1))) {
echo "String 1 not acceptable acceptable";
}
?>
preg_match('/\\s/',$username)
将检查空格
!ctype_alnum(str_replace($valid_symbols, '', $string1))
将检查valid_symbols
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.