dongliyan9190 2014-07-25 06:50
浏览 178
已采纳

PHP正则表达式允许特殊字符,但没有任何空格

I have the following Regex to allow alphanumeric characters and following special characters

/()-

The Regular expression is

/[^A-Za-z0-9-()-/]/

The complete method is

public function ValidateNumber($number)
{
    $return = true;
    $matches = null;
    if((preg_match('/[^A-Za-z0-9-/()-]/', $number, $matches)) > 0)
    {
       $return = false; 
    }
    return $return;
}

Above method woks fine, but also return TRUE if number has space. When i remove '/' from Regex then if number has 'space' in it then it returns FALSE.

So seems some issue with '/' in Regex.

Please advise some solution

  • 写回答

4条回答 默认 最新

  • douxiaomang5640 2014-07-25 06:52
    关注

    Regex to allow alphanumeric characters and the the above mentioned special characters /()-,

    ^[A-Za-z0-9()\/-]+$
    

    ^ inside(at the strat of) chracter class means not. So your regex allows any character not of the ones mentioned inside the character class. And also it's better to escape / inside the character class and always consider in putting - at the start or end of the character class. To allow one ore more characters which was mentioned inside char class then you need to add + after the character class.

    Explanation:

    ^                        the beginning of the string
    [A-Za-z0-9()\/-]+        any character of: 'A' to 'Z', 'a' to 'z',
                             '0' to '9', '(', ')', '\/', '-' (1 or more
                             times)
    $                        before an optional 
    , and the end of the
                             string
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?