0
0
PhpHow-ToBeginner · 3 min read

How to Validate Phone Number Using Regex in PHP

To validate a phone number in PHP, use the preg_match function with a regex pattern that matches your phone number format. For example, preg_match('/^\+?[0-9]{10,15}$/', $phone) checks if the phone number contains 10 to 15 digits and an optional leading plus sign.
📐

Syntax

The main function to validate a phone number using regex in PHP is preg_match. It takes two main arguments: the regex pattern and the string to test.

  • preg_match('/pattern/', $string) returns 1 if the pattern matches, 0 if not.
  • The regex pattern defines the rules for a valid phone number, such as digits, length, and optional symbols.
php
preg_match('/^\+?[0-9]{10,15}$/', $phone)
💻

Example

This example shows how to check if a phone number is valid using a regex pattern that allows an optional plus sign followed by 10 to 15 digits.

php
<?php
$phone = '+12345678901';
if (preg_match('/^\+?[0-9]{10,15}$/', $phone)) {
    echo "Valid phone number.";
} else {
    echo "Invalid phone number.";
}
?>
Output
Valid phone number.
⚠️

Common Pitfalls

Common mistakes when validating phone numbers with regex include:

  • Using too strict or too loose patterns that reject valid numbers or accept invalid ones.
  • Not accounting for spaces, dashes, or parentheses often used in phone numbers.
  • Ignoring international formats or country codes.

Adjust your regex based on the expected phone number format.

php
<?php
// Wrong: Does not allow plus sign or spaces
$wrongPattern = '/^[0-9]{10}$/';
// Right: Allows optional plus and spaces or dashes
$rightPattern = '/^\+?[0-9\s\-]{10,15}$/';
?>
📊

Quick Reference

Regex PatternDescription
/^\+?[0-9]{10,15}$/Optional plus sign, 10 to 15 digits only
/^\+?[0-9\s\-]{10,15}$/Optional plus, digits, spaces, dashes allowed
/^[0-9]{10}$/Exactly 10 digits, no symbols or spaces
/^\+\d{1,3}\s?\d{4,14}(?:x.+)?$/International format with optional extension

Key Takeaways

Use preg_match with a regex pattern to validate phone numbers in PHP.
Adjust your regex to match the expected phone number format including symbols and length.
Test your regex with different phone number examples to avoid common mistakes.
Remember that phone numbers vary by country, so tailor your pattern accordingly.
Avoid overly strict patterns that reject valid numbers or too loose ones that accept invalid input.