user3225440
user3225440

Reputation: 231

Using preg_match to validate phone number format

I am having issues making a function that validates that a phone number is in this exact format(xxx)xxx-xxxx.

My attempt was to use preg_match to confirm that the number is in the given format, but I'm having issues with the pattern.

preg_match("/^([0-9]){3}[0-9]{3}-[0-9]{4}$/", $field)

I think my issue is that I don't know how to handle parenthesis in preg_match.

Upvotes: 0

Views: 9121

Answers (2)

manish1706
manish1706

Reputation: 1599

You can have all this number validation by this code,

<?php
$array = array(
'0 000 (000) 000-0000',
'000 (000) 000-0000',
'0-000-000-000-0000',
'000 (000) 000-0000',
'000-000-000-0000',
'000-00-0-000-0000',
'0000-00-0-000-0000',
'+000-000-000-0000',
'0 (000) 000-0000',
'+0-000-000-0000',
'0-000-000-0000',
'000-000-0000',
'(000) 000-0000',
'000-0000',
'+9981824139',
9981824139,
919981824139,
'+919981824139',
'qwqwqwqwqwqwqw'
);

foreach($array AS $no){    
            var_dump( ( preg_match( '/\d?(\s?|-?|\+?|\.?)((\(\d{1,4}\))|(\d{1,3})|\s?)(\s?|-?|\.?)((\(\d{1,3}\))|(\d{1,3})|\s?)(\s?|-?|\.?)((\(\d{1,3}\))|(\d{1,3})|\s?)(\s?|-?|\.?)\d{3}(-|\.|\s)\d{4}/', $no )
            ||
            preg_match('/([0-9]{8,13})/', str_replace(' ', '', $no))
            ||
            ( preg_match('/^\+?\d+$/', $no) && strlen($no) >= 8 && strlen($no) <= 13 ) )
          );
    }

//var_dump (preg_match('/([0-9]{8,12})/', '99818241') );
//var_dump( strlen(9981) );

//var_dump (preg_match('/^\+?\d+$/', '+12345678') );
//var_dump (preg_match('/^\+?\d+$/', '12345678') );

This will Validate your all type of phone number and output would be

bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
bool(false)

Upvotes: 1

ElefantPhace
ElefantPhace

Reputation: 3814

You need to escape parenthesis : \( and \)

try this:

$n = "(123)456-3890";
$p = "/\(\d{3}\)\d{3}-\d{4}/";

preg_match($p,$n,$m);

var_dump($m);

Upvotes: 1

Related Questions