【问题标题】:Allow only [a-z][A-Z][0-9] in string using PHP使用 PHP 在字符串中只允许 [a-z][A-Z][0-9]
【发布时间】:2010-05-24 11:05:39
【问题描述】:

如何获取只包含a到z、A到Z、0到9和一些符号的字符串?

【问题讨论】:

  • 请提供更多细节。你有什么需求?
  • 这是一个模糊的问题,但没有必要将其否决。周围有真的不好的问题可以使用这种处理方法,但这不是其中之一。
  • 我的字符串是 ��S�o�n�u���N�i�g�a�m�,�S�a�n�d�h�a�v ⅰ.我想消除符号...
  • 像这样使用,$strchr = "��S�o�n�u�N�i�g�a�m,�S�i�n�d哈维”; $bodytag = str_replace("�", "", $strchr);
  • 很好用...这已经有效...我刚刚重新启动我的 mozilla...我明白了..非常感谢大家...

标签: php regex


【解决方案1】:

你可以像这样过滤它:

$text = preg_replace("/[^a-zA-Z0-9]+/", "", $text);

至于一些符号,你应该更多具体

【讨论】:

    【解决方案2】:

    您可以使用preg_match 测试您的字符串(让$str):

    if(preg_match("/^[a-zA-Z0-9]+$/", $str) == 1) {
        // string only contain the a to z , A to Z, 0 to 9
    }
    

    如果您需要更多符号,可以在] 之前添加它们

    【讨论】:

    • 你说得对,我应该将^ 和$ 中的模式包围起来,以防止与'??abs??' 匹配,并且整个使用/ 分隔符。抱歉,谢谢。
    【解决方案3】:

    快捷方式如下:

    if (preg_match('/^[\w\.]+$/', $str)) {
        echo 'Str is valid and allowed';
    } else
        echo 'Str is invalid';
    

    这里:

    // string only contain the a to z , A to Z, 0 to 9 and _ (underscore)
    \w - matches [a-zA-Z0-9_]+
    

    希望对你有帮助!

    【讨论】:

      【解决方案4】:

      不需要正则表达式,你可以使用Ctype函数:

      在你的情况下使用ctype_alnum,例如:

      if (ctype_alnum($str)) {
          //...
      }
      

      例子:

      <?php
      $strings = array('AbCd1zyZ9', 'foo!#$bar');
      foreach ($strings as $testcase) {
          if (ctype_alnum($testcase)) {
              echo 'The string ', $testcase, ' consists of all letters or digits.';
          } else {
              echo 'The string ', $testcase, ' don\'t consists of all letters or digits.';
      
          }
      }
      

      在线示例:https://ideone.com/BYN2Gn

      【讨论】:

        【解决方案5】:

        实现这一目标的最佳和最灵活的方法是使用正则表达式。 但我不确定如何在 PHP 中做到这一点,但这篇文章可以提供帮助。 link

        【讨论】:

          【解决方案6】:

          这两个正则表达式都应该这样做:

          $str = preg_replace('~[^a-z0-9]+~i', '', $str);
          

          或者:

          $str = preg_replace('~[^a-zA-Z0-9]+~', '', $str);
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2016-06-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2016-12-22
            • 2016-03-25
            • 2020-04-13
            相关资源
            最近更新 更多