doulong2782
2017-04-20 05:07
浏览 159
已采纳

PHP:如何检查字符串是不是数字,但可以包含空格?

The goal is to validate a number that is numeric and may or may not contain spaces.

Eg, both '1800 123 456' and '1800123456' are acceptable.

Checking to see if it is not numeric is easy:

if(!is_numeric($phone_number)) {
  //display error message
}

But I am stuck as to how to pass it with spaces.

Would anyone be able to point me in the right direction with this?

图片转代码服务由CSDN问答提供 功能建议

目标是验证一个数字的数字,可能包含也可能不包含空格。

例如,'1800 123 456'和'1800123456'都可以接受。

检查它是不是数字很容易:

  if(!is_numeric($ phone_number)){
 //显示错误消息
} 
   
 
 

但我不知道如何 用空格传递它。

有人能指出我正确的方向吗?

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • douduan6731 2017-04-20 05:11
    已采纳

    Just check without the spaces:

    <?php
    if(!is_numeric(str_replace(" ", "", $phone_number))) {
      //display error message
    }
    

    Or, if you want the overhead of a regular expression:

    <?php
    if (preg_match("/[^0-9 ]/", $phone_number)) {
        //display error message
    }
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • donglian7879 2017-04-20 05:10

    Try this code snippet here

    Regex: ^[\d]{4}\s+[\d]{3}\s+[\d]{3}|[\d]{10}$

    [\d]{4}\s+[\d]{3}\s+[\d]{3} Example: Format of type this 1800 123 456

    [\d]{10} Example: Format of type this 1800123456

    <?php
    ini_set('display_errors', 1);
    $phone_number='1800 123 456';
    if(preg_match("/^[\d]{4}\s+[\d]{3}\s+[\d]{3}|[\d]{10}$/",$phone_number)) 
    {
         echo "matched";
    }
    else
    {
         echo "not matched";
    }
    
    评论
    解决 无用
    打赏 举报
  • douqian5920 2017-04-20 05:11

    You can use following checks:

    //eliminate every char except 0-9
    $justNums = preg_replace("/[^0-9]/", '', $string);
    
    //eliminate leading 1 if its there
    if (strlen($justNums) == 11) $justNums = preg_replace("/^1/", '',$justNums);
    
    //if we have 10 digits left, it's probably valid.
    if (strlen($justNums) == 10) $isPhoneNum = true;
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题