PHP preg_match - 仅允许使用字母数字字符串和__字符

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)

说明:

  • [] =>字符类定义
  • ^ =>否定班级
  • az =>从'a'到'z'的字符
  • _ =>下划线
  • - =>连字符' - '(你需要逃脱它)
  • 0-9 =>数字(从零到九)

正则表达式末尾的'i'修饰符用于'不区分大小写',如果你没有说你需要在代码中添加大写字符之前做AZ

  • @wlin你需要在charecter类定义中添加`\ x {4e00} - \x {9fa5}`,同时添加`u`修饰符将字符串和模式视为UTF-8.它看起来像这样`/ [^ a-z _\ - 0-9\x {4e00} - \x {9}}/ui`你可以在这里测试它:https://xrg.es/#1qvtb7n (2认同)

mat*_*ino 18

if(!preg_match('/^[\w-]+$/', $string1)) {
   echo "String 1 not acceptable acceptable";
   // String2 acceptable
}
Run Code Online (Sandbox Code Playgroud)

  • @matino:你需要锚定你的正则表达式,除非它匹配`a; b` (2认同)

Epi*_*any 5

这是 UTF-8 世界公认的答案的一个等价物。

if (!preg_match('/^[\p{L}\p{N}_-]+$/u', $string)){
  //Disallowed Character In $string
}
Run Code Online (Sandbox Code Playgroud)

解释:

  • [] => 字符类定义
  • p{L} => 匹配来自任何语言的任何类型的字母字符
  • p{N} => matches any kind of numeric character
  • _- => matches underscore and hyphen
  • + => Quantifier — Matches between one to unlimited times (greedy)
  • /u => Unicode modifier. Pattern strings are treated as UTF-16. Also causes escape sequences to match unicode characters

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.