[英]PHP preg_match - only allow alphanumeric strings and - _ characters
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
}
Code: 码:
if(preg_match('/[^a-z_\-0-9]/i', $string))
{
echo "not valid string";
}
Explanation: 说明:
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 AZ 正则表达式末尾的'i'修饰符用于'不区分大小写',如果你没有说你需要在代码中添加大写字符之前做AZ
if(!preg_match('/^[\w-]+$/', $string1)) {
echo "String 1 not acceptable acceptable";
// String2 acceptable
}
Here is one equivalent of the accepted answer for the UTF-8 world. 这是UTF-8世界接受的答案的一个等价物。
if (!preg_match('/^[\p{L}\p{N}_-]+$/u', $string)){
//Disallowed Character In $string
}
Explanation: 说明:
Note, that if the hyphen is the last character in the class definition it does not need to be escaped . 请注意,如果连字符是类定义中的最后一个字符,则不需要对其进行转义 。 If the dash appears elsewhere in the class definition it needs to be escaped , as it will be seen as a range character rather then a hyphen.
如果破折号出现在类定义的其他位置,则需要对其进行转义 ,因为它将被视为范围字符而不是连字符。
Here is a funky non-regex method using str_word_count() : 这是一个使用str_word_count()的时髦非正则表达式方法:
if($string===str_word_count($string,1,'-_0...9')[0]){
// ^^^^^^^--- characters to allow, see documentation
echo "pass";
}else{
echo "fail";
}
View the Demo Link where I show how different inputs result in different output arrays. 查看演示链接 ,其中显示了不同输入如何产生不同的输出数组。
Why to use regex? 为什么要使用正则表达式? PHP has some built in functionality to do that
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)
will check for blank space preg_match('/\\s/',$username)
将检查空格
!ctype_alnum(str_replace($valid_symbols, '', $string1))
will check for valid_symbols !ctype_alnum(str_replace($valid_symbols, '', $string1))
将检查valid_symbols
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.