Skip to content

Instantly share code, notes, and snippets.

@gocs
Last active October 7, 2021 05:27
Show Gist options
  • Save gocs/617a61e301345aacc39208d7ef5c6d1d to your computer and use it in GitHub Desktop.
Save gocs/617a61e301345aacc39208d7ef5c6d1d to your computer and use it in GitHub Desktop.
validate or format phone number in php
/**
* FormatPhone formats phone number
* @param string $number phone number
*
* @return int formatted phone number
*
*/
function FormatPhone($phone)
{
$rx = "/
(1)?\D* # optional country code
(\d{3})?\D* # optional area code
(\d{3})\D* # first three
(\d{4}) # last four
(?:\D+|$) # extension delimiter or EOL
(\d*) # optional extension
/x";
preg_match($rx, $phone, $matches);
if(!isset($matches[0])) {
return "the given number is not a valid phone number";
}
$area = $matches[2];
$three = $matches[3];
$four = $matches[4];
return "$area$three$four";
}
/**
* ValidatePhone validates phone number
* @param int $number phone number
*
* @return string error message if there's any
*
*/
function ValidatePhone($number) {
if (empty($number)) {
return "There is no Phone number given. (UserController)\n";
}
// eliminate every char except 0-9
$justNums = preg_replace("/[^0-9]/", '', $number);
// eliminate leading 1 if its there
if (strlen($justNums) == 11) $justNums = preg_replace("/^1/", '',$justNums);
// if we don't have 10 digits left, let's say it's invalid.
if(strlen($justNums) != 10) {
return "Phone number is invalid. (UserController)\n";
}
return "";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment