Last active
October 7, 2021 05:27
-
-
Save gocs/617a61e301345aacc39208d7ef5c6d1d to your computer and use it in GitHub Desktop.
validate or format phone number in php
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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"; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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