PHP: Validation of US Phone numbers
Try This
<?php
class Validation {
public $default_filters = array(
'phone' => array(
'regex'=>'/^\(?(\d{3})\)?[-\. ]?(\d{3})[-\. ]?(\d{4})$/',
'message' => 'is not a valid US phone number format.'
)
);
public $filter_list = array();
function Validation($filters=false) {
if(is_array($filters)) {
$this->filters = $filters;
} else {
$this->filters = array();
}
}
function validate($filter,$value) {
if(in_array($filter,$this->filters)) {
if(in_array('default_filter',$this->filters[$filter])) {
$f = $this->default_filters[$this->filters[$filter]['default_filter']];
if(in_array('message',$this->filters[$filter])) {
$f['message'] = $this->filters[$filter]['message'];
}
} else {
$f = $this->filters[$filter];
}
} else {
$f = $this->default_filters[$filter];
}
if(!preg_match($f['regex'],$value)) {
$ret = array();
$ret[$filter] = $f['message'];
return $ret;
}
return true;
}
}
//example usage
$validation = new Validation();
echo nl2br(print_r($validation->validate('phone','555-555-1212'),true));
echo nl2br(print_r($validation->validate('phone','(555)-555-1212'),true));
echo nl2br(print_r($validation->validate('phone','555 555 1212'),true));
echo nl2br(print_r($validation->validate('phone','555.555.1212'),true));
echo nl2br(print_r($validation->validate('phone','(555).555.1212'),true));
echo nl2br(print_r($validation->validate('phone','(555)---555.1212'),true));//will not match
?>
Validating US phone number with php/regex
You can resolve this using a lookahead assertion. Basically what we're saying is I want a series of specific letters, (e, ex, ext, x, extension) followed by one or more number. But we also want to cover the case where there's no extension at all.
Side Note, you don't need brackets
around single characters like [\s] or
that [x] that follows. Also, you can group
characters that are meant to be in the same
spot, so instead of \s?\.?/?, you can
use [\s\./]? which means "one of any of those
characters"
Here's an update with regex that resolves your comment here as well. I've added the explanation in the actual code.
<?php
$sPattern = "/^
(?: # Area Code
(?:
\( # Open Parentheses
(?=\d{3}\)) # Lookahead. Only if we have 3 digits and a closing parentheses
)?
(\d{3}) # 3 Digit area code
(?:
(?<=\(\d{3}) # Closing Parentheses. Lookbehind.
\) # Only if we have an open parentheses and 3 digits
)?
[\s.\/-]? # Optional Space Delimeter
)?
(\d{3}) # 3 Digits
[\s\.\/-]? # Optional Space Delimeter
(\d{4})\s? # 4 Digits and an Optional following Space
(?: # Extension
(?: # Lets look for some variation of 'extension'
(?:
(?:e|x|ex|ext)\.? # First, abbreviations, with an optional following period
|
extension # Now just the whole word
)
\s? # Optionsal Following Space
)
(?=\d+) # This is the Lookahead. Only accept that previous section IF it's followed by some digits.
(\d+) # Now grab the actual digits (the lookahead doesn't grab them)
)? # The Extension is Optional
$/x"; // /x modifier allows the expanded and commented regex
$aNumbers = array(
'123-456-7890x123',
'123.456.7890x123',
'123 456 7890 x123',
'(123) 456-7890 x123',
'123.456.7890x.123',
'123.456.7890 ext. 123',
'123.456.7890 extension 123456',
'123 456 7890',
'123-456-7890ex123',
'123.456.7890 ex123',
'123 456 7890 ext123',
'456-7890',
'456 7890',
'456 7890 x123',
'1234567890',
'() 456 7890'
);
foreach($aNumbers as $sNumber) {
if (preg_match($sPattern, $sNumber, $aMatches)) {
echo 'Matched ' . $sNumber . "\n";
print_r($aMatches);
} else {
echo 'Failed ' . $sNumber . "\n";
}
}
?>
And The Output:
Matched 123-456-7890x123
Array
(
[0] => 123-456-7890x123
[1] => 123
[2] => 456
[3] => 7890
[4] => 123
)
Matched 123.456.7890x123
Array
(
[0] => 123.456.7890x123
[1] => 123
[2] => 456
[3] => 7890
[4] => 123
)
Matched 123 456 7890 x123
Array
(
[0] => 123 456 7890 x123
[1] => 123
[2] => 456
[3] => 7890
[4] => 123
)
Matched (123) 456-7890 x123
Array
(
[0] => (123) 456-7890 x123
[1] => 123
[2] => 456
[3] => 7890
[4] => 123
)
Matched 123.456.7890x.123
Array
(
[0] => 123.456.7890x.123
[1] => 123
[2] => 456
[3] => 7890
[4] => 123
)
Matched 123.456.7890 ext. 123
Array
(
[0] => 123.456.7890 ext. 123
[1] => 123
[2] => 456
[3] => 7890
[4] => 123
)
Matched 123.456.7890 extension 123456
Array
(
[0] => 123.456.7890 extension 123456
[1] => 123
[2] => 456
[3] => 7890
[4] => 123456
)
Matched 123 456 7890
Array
(
[0] => 123 456 7890
[1] => 123
[2] => 456
[3] => 7890
)
Matched 123-456-7890ex123
Array
(
[0] => 123-456-7890ex123
[1] => 123
[2] => 456
[3] => 7890
[4] => 123
)
Matched 123.456.7890 ex123
Array
(
[0] => 123.456.7890 ex123
[1] => 123
[2] => 456
[3] => 7890
[4] => 123
)
Matched 123 456 7890 ext123
Array
(
[0] => 123 456 7890 ext123
[1] => 123
[2] => 456
[3] => 7890
[4] => 123
)
Matched 456-7890
Array
(
[0] => 456-7890
[1] =>
[2] => 456
[3] => 7890
)
Matched 456 7890
Array
(
[0] => 456 7890
[1] =>
[2] => 456
[3] => 7890
)
Matched 456 7890 x123
Array
(
[0] => 456 7890 x123
[1] =>
[2] => 456
[3] => 7890
[4] => 123
)
Matched 1234567890
Array
(
[0] => 1234567890
[1] => 123
[2] => 456
[3] => 7890
)
Failed () 456 7890
Regex to Validate Phone Numbers in php
One option could be using optional parts at the start of the pattern:
^\+?0*(?:91-)?\K(?:91)?[6-9][0-9]{9}$
^
Start of string\+?0*(?:91-)?
Optionally match+
, 0+ times a0
or91-
\K
Forget what was matched(?:91)?
Optionally match91
[6-9][0-9]{9}
Match a digit 6-9 and 9 digits 0-9$
End of string
Regex demo | Php demo
If you don't want to use anchors ^
and $
you could use lookaround assertions to make sure what is directly on the left and right is not a non whitespace char:
(?<!\S)\+?0*(?:91-)?\K(?:91)?[6-9][0-9]{9}(?!\S)
Regex demo | Php demo
regex to validate phone number
^\+?(\d[.\- ]*){9,14}(e?xt?\d{1,5})?$
Explanation;
^
Asserts start of string\+?
Matches an optional plus(\d[.\- ]*){9,14}
between 9 and 14 single digits, possibly seperated by spaces, dots, or dashes.(e?xt?\d{1,5})?
Optionally a x possibly preceeded by an e or followed by a t. The letters always followed by between 1 and 5 numbers.$
Asserts end of the string
PHP - Validate phone number
Add a space and escape the round brackets:
^\([0-9]{3}\)[- ][0-9]{3}-[0-9]{4}$
^^ ^^^^^^
See the demo
I added a character class [- ]
just in case there can be either a space or a hyphen after the area code. Parentheses must be escaped in order to be treated as literal symbols and not as a grouping construct.
PHP demo:
$phone = '(123) 458-1542';
if(preg_match('~^\([0-9]{3}\)[- ][0-9]{3}-[0-9]{4}$~', $phone)) {
echo "Matched: $phone";
}
How to validate phone number using PHP?
Since phone numbers must conform to a pattern, you can use regular expressions to match the entered phone number against the pattern you define in regexp.
php has both ereg and preg_match() functions. I'd suggest using preg_match() as there's more documentation for this style of regex.
An example
$phone = '000-0000-0000';
if(preg_match("/^[0-9]{3}-[0-9]{4}-[0-9]{4}$/", $phone)) {
// $phone is valid
}
regex for validating a phone number starting with +254
The correct syntax should be:
preg_match('/^\+254\d{9}/', $phonenumber);
Phone Number Regex Conditions
I would use this regex pattern for Singapore numbers:
^(?:\+65)?[689][0-9]{7}$
Sample script:
$number = "+6587654321";
if (preg_match("/^(?:\+65)?[689][0-9]{7}$/", $number)) {
echo "MATCH";
}
Validating USA cell/mobile phone numbers with regex?
you can use Google's phone number handling library. Maybe better than regex.
Here: https://github.com/giggsey/libphonenumber-for-php
Related Topics
Does the Order of Class Definition Matter in PHP
Php: Split Multibyte String (Word) into Separate Characters
Remove Double Quote in JSON_Encode()
How to Prevent from Printscreen of My Webpage
Can't Set PHP Cookie on the Same Page
Continuing Overflowed Text in a Different Div
How to Get Data in Function Extend Controller
Php's Array_Map Including Keys
Getting the Value of an Extra Pivot Table Column Laravel
Determine If Business Is Open/Closed Based on Business Hours
How to Call a PHP Function from Ajax
Adding a Namespace When Using Simplexmlelement
Algorithm for Generating a Random Number
How to Send Emails with Arabic Content via PHP's Mail Function
Disable Add to Cart Button for an Array of Products Ids in Woocommerce
How to Convert All Images to Jpg Format in PHP
How to Retrieve Comments from Within an Xml Document in PHP
Composer Install Error - Requires Ext_Curl When It's Actually Enabled