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 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献