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?

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
}

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";
}

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;