【问题标题】:check if there are non-letters or non-numbers in the string检查字符串中是否有非字母或非数字
【发布时间】:2011-12-20 14:45:14
【问题描述】:

如何检测字符串中的非数字或非字母?

KY4R5EHCN5W476XXO5ER - 返回true

KY4R5EHCN5W472X**@**O5ER - 返回false

我知道答案是使用正则表达式,但我不知道该怎么做。我很讨厌正则表达式。任何帮助将不胜感激。

谢谢!

【问题讨论】:

    标签: php regex string validation


    【解决方案1】:
    if (preg_match('/[^A-Z0-9]/', $string)) {
        ... some char other than A-Z, 0-9 detected
    }
    

    【讨论】:

    • 你需要 i 在末尾,否则你不会得到小写字符。
    • 或者只是将 a-z 添加到字符类中。无论如何,OP 的样本中都没有小写字母。
    • 是的,无论哪种方式都可以。在 OP 中,他只是说 detect a non number or non letter,尽管该示例只有大写字母。
    【解决方案2】:
    if (preg_match('/[^a-z0-9]/i', $subject)) {
        // Invalid characters
    } else {
        // Only letters and numbers
    }
    

    【讨论】:

    • 您可以将课程简化为 ^a-z0-9,因为您最后使用的是 i。
    【解决方案3】:

    你可以用这个:

    if (preg_match('/^([a-z0-9]+)$/iu', $string))
    {
       // all alpha and digits
    }
    else
    {
       // not all alpha and digits
    }
    

    【讨论】:

    • 完美!谢谢!也许我现在应该学习正则表达式,因为它有点酷。再次感谢
    • @LeysamRosario 很高兴为您提供帮助(就像所有回答您问题的人一样)
    【解决方案4】:
    (preg_match('/^[A-Z0-9]+$/', $string) == 0)
    

    如果要包含小写字符,请更改为 a-zA-Z0-9

    如果字符串只包含 A-Z 和 0-9,这应该返回 true。

    或

    (preg_match('/[^A-Z0-9]/', $string) != 0)
    

    应该做的差不多。

    【讨论】:

      【解决方案5】:

      ctype_alnum() 在检测字符串是否为纯字母数字(字母和数字)方面将比正则表达式快得多。

      $str1 = 'KY4R5EHCN5W476XXO5ER';
      $str2 = 'KY4R5EHCN5W472X*@*O5ER' ;
      
      foreach (array($str1, $str2) as $str){ 
      
          if (ctype_alnum($str)) {
              echo "$str is alphanumeric\n" ;
          }
          else {
              echo "$str is not just alphanumeric\n";
          }
      }
      

      但是,请务必使用此处给出的正则表达式,因为这是一项有用的技能,尤其是当您后来决定还需要检查其他字符(如破折号)时。你会发现The Regex Coach 在试验它们时非常有用。

      $str = 'KY4R5EHCN5W476XXO5ER' ;
      $ut = microtime(true) ;
      
      for ($i = 0 ; $i < 100000; $i++) {
          $res = ctype_alnum($str) ;
      }
      
      $utCtype = microtime(true) ;
      
      for ($i = 0 ; $i < 100000; $i++) {
          $res = preg_match('/[a-z0-9]/i', $str) ;
      } 
      
      $utEnd = microtime(true) ;
      
      $utDiffCtype = $utCtype - $ut ;
      $utDiffPreg = $utEnd - $utCtype;
      
      echo "ctype: $utDiffCtype, preg: $utDiffPreg" ;
      

      【讨论】:

      • 有趣的比较。结论是,两种方法之间的性能差异可以忽略不计。
      【解决方案6】:

      使用这个正则表达式来兼容 unicode:

      /^[\p{L}\p{N}]+$/u
      

      【讨论】:

        猜你喜欢
        • 2012-12-27
        • 2019-03-31
        • 2016-05-19
        • 2019-06-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多