Validate a Phone Number

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

The Expression

^[+]?([0-9]?)[(|s|-|.]?([0-9]{3})[)|s|-|.]*([0-9]{3})[s|-|.]*([0-9]{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('/^[+]?([0-9]?)[(|s|-|.]?([0-9]{3})[)|s|-|.]*([0-9]{3})[s|-|.]*([0-9]{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('/^[+]?([0-9]?)[(|s|-|.]?([0-9]{3})[)|s|-|.]*([0-9]{3})[s|-|.]*([0-9]{4})$/', $string, $matches);
$new_string = $matches[2] . '-' . $matches[3] . '-' . $matches[4];

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

There you go! If you find you need another format or you’d like a different type of string to validate, please send me an email and I will respond as quickly as I can.