Lee*_*ice 26 php regex preg-match
我需要正则表达式来检查字符串是否只包含数字,字母,连字符或下划线
$string1 = "This is a string*";
$string2 = "this_is-a-string";
if(preg_match('******', $string1){
echo "String 1 not acceptable acceptable";
// String2 acceptable
}
Run Code Online (Sandbox Code Playgroud)
SER*_*PRO 86
码:
if(preg_match('/[^a-z_\-0-9]/i', $string))
{
echo "not valid string";
}
Run Code Online (Sandbox Code Playgroud)
说明:
正则表达式末尾的'i'修饰符用于'不区分大小写',如果你没有说你需要在代码中添加大写字符之前做AZ
mat*_*ino 18
if(!preg_match('/^[\w-]+$/', $string1)) {
echo "String 1 not acceptable acceptable";
// String2 acceptable
}
Run Code Online (Sandbox Code Playgroud)
这是 UTF-8 世界公认的答案的一个等价物。
if (!preg_match('/^[\p{L}\p{N}_-]+$/u', $string)){
//Disallowed Character In $string
}
Run Code Online (Sandbox Code Playgroud)
解释:
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.