【问题标题】:preg_match to only allow 10 digits an no special characters or spacespreg_match 只允许 10 位数字,没有特殊字符或空格
【发布时间】:2013-08-09 22:56:24
【问题描述】:

我有以下功能:preg_match('/^[0-9]{10}$/' 只允许 10 位数字。但是,如果我输入 041 123456 它会接受它。我如何防止空格?我希望用户仅将电话号码输入为 041123456。不允许有空格或特殊字符。

我使用的代码是

If( ($fax_1_length != 0) | preg_match('/^[0-9]{10}$/', $fax_1) ){
    $fax_1_lenght_valid = true;
    $fax_1 = mysql_real_escape_string(stripslashes($_POST['fax_1']));   
    }
    else
    {
            $mistakes[] = 'ERROR - Your 1st Fax Number should only contain numbers or is empty.';
    }

【问题讨论】:

    标签: regex


    【解决方案1】:

    问题是这一行:

    if( ($fax_1_length != 0) | preg_match('/^[0-9]{10}$/', $fax_1) )
    

    | 用于按位或运算。

    您应该使用&& 而不是|

    if( ($fax_1_length > 0) && preg_match('/^[0-9]{10}$/', $fax_1) )
    

    当长度 > 0 && 电话号码仅包含 10 位数字时,如果阻塞将执行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多