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

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?

  • 写回答

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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?