Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to validate a phone number

Short answer

Remove everything except digits and check the length:

<?php
 
function isPhone(string $phone): bool
{
    $digits = preg_replace('/\D/', '', $phone);
 
    return strlen($digits) >= 10 && strlen($digits) <= 15;
}
 
var_dump(isPhone('+1 (202) 555-01-23'));
var_dump(isPhone('555-01'));

Output:

bool(true)
bool(false)

One form for storage

In the database the number is stored as digits with a plus sign:

<?php
 
echo '+' . preg_replace('/\D/', '', '+44 (20) 7946-0958');

Output:

+442079460958

Do not be too strict

Number formats differ between countries. A rigid pattern turns away real users; for precise validation there is the giggsey/libphonenumber-for-php library.

Functions used in this recipe

  • preg_match — Tests a string against a regular expression.
  • preg_replace — Replaces everything that matches a regular expression.
  • strlen — Returns the length of a string in bytes.

Thanks for reading!

Donate to the site — we work hard for you.