I'm looking for some way to validate telephone numbers in PHP, which may be entered in any of the various formats that exist. If it helps, I'm able to restrict the problem's domain to just U.S. phone numbers (or international numbers - one or the other, but not both).
I've tried looking for custom filters for filter_var()
, an equivalent to strtotime()
for phone numbers, or just plain vanilla parsing libraries, but haven't had much luck.
If needed, I can design a custom solution, but I prefer not to if one already exists, because A) mine will surely not be as robust, and B) I don't like reinventing the wheel.
Use regex, the following will Match things like 3334445555, 333.444.5555, 333-444-5555, 333 444 5555, (333) 444 5555 and all combinations thereof. and then replaces all those with (333) 444-5555
preg_replace('\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})', '(\1) \2-\3', $text);
'Parsing' phone numbers is not a native PHP thing to do.
You need to specify yourself what 'valid' phonenumbers are - this should be done by validating the input up against a specified format or perhaps a regular expression.
There is no way PHP can know what 'a valid phonenumber' is.
I'm not aware of all US phone number formats, but i'm guessing this is a general idea that you can extend:
function validate_phone($phone) {
// replace everything except numbers
$phone = preg_replace('~[^\dx]~', '', $phone);
return preg_match('~^\d{11}(x\d{4})?$~', $phone);
}
// $phone = 12345678901;
$phone = '1-234-567-8901x1234';
$valid = filter_var($phone, FILTER_CALLBACK, array(
'options' => 'validate_phone'
));
if ($valid) {
echo "It's valid!";
};
This code supports or eleven digit numbers(with dashes, spaces, dots inside) and extended format with x2134 suffix.