Validate a Phone Number

This code snippet is a regular expression which checks or validates a phone number.

The Expression

^[+]?([\d]{0,3})?[\(\.\-\s]?([\d]{3})[\)\.\-\s]*([\d]{3})[\.\-\s]?([\d]{4})$

This regular expression will match any of the following U.S. numbers:

  • 555 555 5555
  • (555) 555-5555
  • (555)555-5555
  • 555-555-5555
  • 555.555.5555
  • 5555555555
  • 0-000-000-0000
  • 0.000.000.0000
  • 0 000 000 0000
  • 00000000000
  • +0-000-000-0000
  • +0.000.000.0000
  • +0 000 000 0000
  • +00000000000

Why so many matches? I think it’s better, and easier to take a users input and alter it to our specifications, rather than make the user follow our guidelines.

Validate Function

Here is a quick and simple validation function for a phone number using the regular expression above and PHP’s preg_match() function:

function validate_phone_number( $string ) {
    if ( preg_match( '/^[+]?([\d]{0,3})?[\(\.\-\s]?([\d]{3})[\)\.\-\s]*([\d]{3})[\.\-\s]?([\d]{4})$/', $string ) ) {
        return TRUE;
    } else {
        return FALSE;
    }
}

Modify the Data

After checking to see if the data is correct, we need to format it the way we need/want it. It’s always good to keep everything consistent.

To re-write the data, pass a third parameter to the preg_match() function, I will be using $matches. PHP will save the captures (anything wrapped in parenthesis inside the regex) to that variable, as an array.

$string = "(555) 555-5555";
preg_match( '/^[+]?([\d]{0,3})?[\(\.\-\s]?([\d]{3})[\)\.\-\s]*([\d]{3})[\.\-\s]?([\d]{4})$/', $string, $matches );
$new_string = $matches[2] . '-' . $matches[3] . '-' . $matches[4];

// New String:
// 555-555-5555