Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Quickly checking for telephone number format in input text using PHP?

What's the most efficient way to quickly check for telephone number format from a form input text?

like image 768
ina Avatar asked Jan 25 '26 10:01

ina


2 Answers

easiest way is to strip out everything that is not a number and then count how many digits there are. That way you don't have to force a certain format on the user. As far as how many numbers you should check for...depends on if you are checking for just local numbers, US numbers, international numbers, etc...but for instance:

$number="(123) 123-1234";
if (strlen(preg_replace('~[^0-9]~','',$number)) == 10) {
  // 10 digit number (US area code plus phone number)
}
like image 115
Crayon Violent Avatar answered Jan 28 '26 01:01

Crayon Violent


That really depends on the location. There are different conventions from place-to-place as to the length of the area code and the length of the entire number. Being more permissive would be better.

A regular expression to ensure that it is an optional '+', followed by any number of digits would be the bare minimum. Allowing optional dashes ("-") or spaces separating groups of numbers could be a nice addition. Also, what about extension numbers?

In truth, it's probably best to just check that it includes some numbers.

like image 26
Gian Avatar answered Jan 28 '26 02:01

Gian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!