I want to display an error message if the number doesn't match any number with hyphen, plus sign, space or brackets. No numbers either.
For example:
(012) 123 4567
(012)-123-4567
012-345-6789
123 123 1234
+12 23 213 3456
The above examples all work with this expression:
if (!preg_match("/^[0-9\-]|[\+0-9]|[0-9\s]|[0-9()]*$/", $_POST['tel'])) {
$telErr = "Invalid contact number";
}
But it allows letters, which I do not want.
Example:
+00000000a
The above example is accepted by the expression I have.
Please can someone help me with this.
I first cleanup the string a bit (that avoids useless matches):
$input = preg_replace('/[^0-9+\(\)-]/', '', $_POST['tel']);
I than match an american number +1 (xxx) xxx-xxxx;
if(preg_match('/^(\+1|001)?\(?([0-9]{3})\)?([ .-]?)([0-9]{3})([ .-]?)([0-9]{4})/',$input))
$result = "match: USA";
else $result = "no match";
this allows for quite some input configurations - only your last number would not match (if I'd not do the cleanup first, not because of the international code which is matched, but because of the split in the area-code) all the others go also without cleanup.
This expression'll accept +5number, 5number
"'^(([\+]([\d]{2,}))([0-9\.\-\/\s]{5,})|([0-9\.\-\/\s]{5,}))*$'"
Better regular expression is:
"/^[\+0-9\-\(\)\s]*$/"
It seems to me that what you want to express is in the ballpark of:
\+{0,1}\({0,1}[0-9]{0,3}\){0,1}[ -]{0,1}[0-9]{0,4}[ -]{0,1}[0-9]{0,4}[ -]{0,1}[0-9]{0,4}
that can be reduced to:
(\+?\(?[0-9]{2,3}\)?)([ -]?[0-9]{2,4}){3}
This can be read this way:
\+? //matches existence of +
\(? //matches existence of (
[0-9]{2,3} //matches 2 to 3 numbers
\)? //matches existence of )
([ -]?[0-9]{2,4}){3} //matches a space or a dash with 2 to 4 numbers, 3 times.
This will give you a maximum of 3 + 4 * 3 = 15 numbers without spaces for the phone variable.
But the best way in my opinion is to trim the input and then count it's length.
In RegEx there's always a perfect matching answer, but it doesn't always means it's a good idea to use it. It can be too complicated to maintain or too hard to understand.
SPAIN - ES
preg_match("/^(\+34|0034|34)?[6|7|9][0-9]{8}$/", $phone);
PORTUGAL - PT
preg_match("/^(\+351|00351|351)?[2|9][0-9]{8}$/", $phone);
ANDORRA - AD
preg_match("/^(\+376|00376|376)?[0-9]{6}$/", $phone);
GIBRALTAR - GI
preg_match("/^(\+350|00350|350)?[0-9]{8}$/", $phone);
--
It will be wonderfull have all the country list
Related
I need help with form validation. Specifically for Australian phone numbers. I can only do basic validation using the preg_match() method but I'm stuck with this.
Must start with +614, (04) or 04; then any grouping of 8 more digits
and single spaces is permitted.
That's the validation criteria, any help is appreciated.
if (!preg_match("/^[0-9 ]*$/",$name)) {
$numberErr = "Number format is invalid"
}
that's all I can do I don't know how to add conditions for the start of the number (start with +614, (04) or 04.
Edit: Also need help with credit card validation, validation criteria is:
Any grouping of 12 - 19 numbers and single spaces are permitted.
if(!preg_match('/[0-9]{12}(?:[0-9]{3})?$/', $card)) {
$cardErr = "Invalid card number";
}
I can't find anything that teaches preg_match() method parameters so I honestly don't even know what the above code is doing.
Sorry for my noobness ;)
I am using anchors (^ and $) so that the start and the end of the string are identified. The leading characters are in the first non-capturing group with pipes that represent "OR". The second non-capturing group, contains the "space-tolerant" 8-digit substring.
Let me know if you have any fringe cases that are not handled properly.
Code: (Demo)
$aussie_mobiles = ['+614 1234 5678', '02 11112222', '(04)98765432', '0413572468', '+614 1 2 3 4 5 6 7 8'];
foreach ($aussie_mobiles as $mob) {
echo "$mob: ";
if (preg_match('~^(?:\+614|\(04\)|04)(?: *\d){8}$~', $mob)) {
echo "pass\n";
} else {
echo "fail\n";
}
}
Output:
+614 1234 5678: pass
02 11112222: fail
(04)98765432: pass
0413572468: pass
+614 1 2 3 4 5 6 7 8: pass
I have a bunch of emails that I read as text in my program and they all have phone numbers such as these:
+370 655 54298
+37065782505
37069788505
865782825
65782825
(686) 51852
How would I go about finding them and saving it into a variable?
For now I am doing it like this:
$found = preg_match('^[0-9\-\+]{9,15}^', $text, $num);
But it does not working at all
Have a look at the "libphonenumber" Google Library.
There are two functions you may find useful
isPossibleNumber - quickly guessing whether a number is a possible phonenumber by using only the length information, much faster than a full validation.
isValidNumber - full validation of a phone number for a region using length and prefix information.
This should work https://regex101.com/r/E2PzRN/2
#\+?\(?\d+\)?\s?\d+\s?\d+#
<?php
$regex = '#\+?\(?\d+\)?\s?\d+\s?\d+#';
$x = [
'+370 655 54298',
'+37065782505',
'37069788505',
'865782825',
'hjtgfjtdfjtgdfjt',
'65782825',
'(686) 51852',
];
foreach ($x as $y) {
if (preg_match($regex, $y, $match)) {
echo $match[0] . "\n";
}
}
Check it in action here https://3v4l.org/6AlQa
We distinguish here 3 types of phone numbers.
The first type is this one:
+37065782505
37069788505
865782825
65782825
Here, the beginning + is optional. we thus consider that we have 7 digits minimum for these numbers.
The regular expression obtained is therefore
(\+?[0-9]{7,})
The second type is this one:
+370 655 54298
Here we have a first block consisting of a + followed by 2 to 6 digits and then several other blocks of 2 to 6 digits and separated by spaces.
The regular expression obtained is therefore
(\+[0-9]{2,6}(\s[0-9]{2,6})+)
The last type is this one:
(686) 51852
This is a first block consisting of 2 to 6 digits surrounded by parentheses and then several other blocks of 2 to 6 digits and separated by spaces.
The regular expression obtained is therefore
(\([0-9]{2,6}\)(\s[0-9]{2,6})+)
The complete extraction code is therefore
preg_match_all("#(\+?[0-9]{7,})|(\+[0-9]{2,6}(\s[0-9]{2,6})+)|(\([0-9]{2,6}\)(\s[0-9]{2,6})+)#",$text,$out);
$found = $out[0];
where $found is an array.
I would suggest stripping out '+','(',')',' ' and testing if it is a ctype_digit
remove all characters and test if numeric, this assumes that the result is a phone no, if you were to run this on an email address the result would be false
var_dump(ctype_digit(str_replace([' ', '+', '(', ')'], '', '(686) 51852')));
TRUE
var_dump(ctype_digit(str_replace([' ', '+', '(', ')'], '', 'r#pm.mr')));
FALSE
I am trying to check if a phone number like this exists in using regex.
(001) 33992292
So, I used
if(preg_match("/[0-9\(\)]+/", $row)){
//is phone number
}
But, the problem with this is that, strings containing numbers get passed as well, like foo134#yahoo.com, so how can I evaluate a phone number and exclude # character is strings all together?
UDPATED
/^(\(\d+\))*\s?(\d+\s*)+$/
you missed start string ^ sign and end string $ sign, what else your regex is wrong
because 5545()4535 will also pass match
You need to use anchors in your regular expression, a proper syntax would be:
if(preg_match('~^\(\d{3}\) *\d{8}$~', $row)) { ... }
Telephone numbers are notorious for people to get wrong - and by people I mean programmers.
For example, these are all "common" ways of writing a phone number:
(001) 33992292
001 33992292
00133992292
001 3399 2292
(001) 3399-2292
A saner approach it to just remove everything that isn't a number and check the length:
$phonenumber = "(001) 33992292";
$phonenumber = preg_replace("/[^0-9,.]/", "", $phonenumber );
if (strlen($phonenumber) == 11) {
// do thing
}
I was searching for hours to get a regular expression for matching dimension in a string.
Consider following types of strings,
120x200
100' X 130'
4 acres
0.54
0.488 (90x223)/ GIS0.78
90x160
100x149.7
143.76 X 453.52
6.13 per tax bill
120x378 per tax roll
I want the O/P contain only dimensions, even with 'X' or 'x'
From the above string, the expected output is,
120x200,100' X 130',0,0,90x223,90x160,100x149.7,143.76 X 453.52,0,120x378
Is there any possible reg-ex? or any other alternative?
Thanks
This seems to work:
<?php
$str = <<<EOD
120x200
100' X 130'
4 acres
0.54
0.488 (90x223)/ GIS0.78
90x160
100x149.7
143.76 X 453.52
6.13 per tax bill
120x378 per tax roll
EOD;
$lines = explode("\n", $str);
foreach($lines as $line) {
if (preg_match('/-?(\d+(?:\.\d+)?(\'|ft|yd|m|")?)\s*x\s*-?(\d+(?:\.\d+)?(?:\\2)?)/i', $line, $match)) {
echo "{$match[1]}x{$match[3]}\n";
} else {
echo "0\n";
}
}
You can add more units of measurement into the 3rd parenthesized expression if you want to match more things, but this matches whole numbers, real numbers, and optional units of measurement after.
This should get you started:
\d+(\.\d+)?['"]?\s*[xX]\s*\d+(\.\d+)?['"]?
demo : http://regexr.com?386sf
However,it does not cover all of your cases,as they are too customized to be handled by regex.
I would recommend using a customized method to parse the input with different cases.
I purchased a contact form. Great little thing but I need to convert the validation for the phone number to allow for UK number formats - in other words, to allow for spaces.
Right now it validates without spaces and has a minimum length of 8 characters:
if(is_numeric($phone))
{
if(!$phone || strlen($phone) < 8)
{
$error .= "Please enter your phone number without spaces.<br />";
}
}
else
{
$error .= "Please enter numeric characters in the phone number field.<br />";
}
Phone numbers are typically horrible for regex patterns, which is what you will need.
This pattern for example:
$pattern = "/^(\+44\s?7\d{3}|\(?07\d{3}\)?)\s?\d{3}\s?\d{3}$/";
$match = preg_match($pattern,$input);
if ($match != false) {
// We have a valid phone number
} else {
// We have an invalid phone number
}
That pattern will match with +44 included or not e.g.
all these will match:
07222 555555
(07222) 555555
+44 7222 555 555
These won't
7222 555555
+44 07222 555555
(+447222) 555555
There are a load of sites that offer tutorials / cheat sheets etc. for regular expressions try some of these:
http://regexlib.com/Default.aspx
as well as a very good stack overflow post:
A comprehensive regex for phone number validation
So you just want to allow spaces?
Then you could use str_replace() to ignore spaces, right at the beginning:
$phone = str_replace(' ', '', $phone);
The is_numeric function that you're using isn't really even a suitable choice for American phone numbers. For example it accepts hexadecimal numbers like 0xABCDEF, which it should reject.
For simple text matching like this, regular expressions are often the easiest solution. A regular expression specifies a pattern of text. PHP has functions to let you search for or replace regular expression matches in text.
If you define a phone number as a string of at least 7 characters containing only digits and spaces, the corresponding regular expression would be /^[0-9 ]{7,}$/. The text inside the brackets represents a set of characters, the {7,} indicates that we're looking for at least 7 of these characters in a row, and the ^ and $ indicate that our match should start at the beginning of the string and end at the end of the string. The PHP documentation has a section explaining regular expressions in greater detail.
You would use the preg_match function to
ensure the phone number matched:
if (preg_match('/^[0-9 ]{7,}$/', $phone)) {
This matches all UK formats with a wide variety of punctuation:
^\(?(?:(?:0(?:0|11)\)?[\s-]?\(?|\+)44\)?[\s-]?\(?(?:0\)?[\s-]?\(?)?|0)(?:\d{5}\)?[\s-]?\d{4,5}|\d{4}\)?[\s-]?(?:\d{5}|\d{3}[\s-]?\d{3})|\d{3}\)?[\s-]?\d{3}[\s-]?\d{3,4}|\d{2}\)?[\s-]?\d{4}[\s-]?\d{4}|8(?:00[\s-]?11[\s-]?11|45[\s-]?46[\s-]?4\d))(?:(?:[\s-]?(?:x|ext\.?\s?|\#)\d+)?)$
Extract the various parts using this pattern
^\(?(?:(?:0(?:0|11)\)?[\s-]?\(?|\+)(44)\)?[\s-]?\(?(?:0\)?[\s-]?\(?)?|0)([1-9]\d{1,4}\)?[\s\d-]+)(?:((?:x|ext\.?\s?|\#)\d+)?)$
The country code is in $1 (and is null for national format). The NSN is in $2. The optional extension is in $3.
Remove all non-digits from $2 for further processing. The next step is to make sure the NSN is in a valid range and is a valid length (either 9 or 10 digits, depending on the range).
The list of patterns is too long to reproduce here but is available at:
http://aa-asterisk.org.uk/index.php/Regular_Expressions_for_Validating_and_Formatting_GB_Telephone_Numbers
You could parse the input to an integer, then validate for the correct number of digits;
$mobileNumber = intval($mobileNumber);
if (preg_match('/(^\d{12}$)|(^\d{10}$)/',$mobileNumber)==TRUE) {
//number has the right number of digits for a UK mobile number
} else {
//number does not have the right number of digits
}
Explained;
$mobileNumber = intval($mobileNumber);
This removes all non numerical characters from the string, and leading zero (eg spaces, brackets, plus signs, decimals etc);
*if (preg_match('/(^\d{12}$)|(^\d{10}$)/',$mobileNumber)==TRUE) {*
This regular expression then checks that the string contains either 12 or 10 digits which would cover 447712345678 (12 digits) or 7791234567 (10 digits). It is matched in two sub clauses (^\d{12}$) or (^\d{10}$) the carat (^) and dollar ($) represent to match everything from the very beginning (^) and to the very end ($) of the string. the \d represents any digit, and the following {12} means match the previous statement that number of times.
This does not mean that the number is valid, you could use an API like twillio to do additional validation of the numebr https://www.twilio.com/help/faq/sms/does-twilio-check-to-see-if-phone-numbers-can-receive-sms
For example;
$mobileNumber = '+447791234567';
$mobileNumber = intval($mobileNumber); //$mobileNumber is now 447791234567
if (preg_match('/(^\d{12}$)|(^\d{10}$)/',$mobileNumber)==TRUE) {
//$mobileNumber matches (^\d{12}$) and is valid
}
You could also add a check to ensure that number starts with either '07' or '447', required for UK mobiles, like this;
function isValidMobile($aNumber){
$aNumber = intval($aNumber);
return preg_match('/(^\d{12}$)|(^\d{10}$)/', $aNumber) && preg_match('/(^7)|(^447)/', $aNumber);
}
the intval removes leading zero,so the regular expression checks for a leadin 7 or 447.
I have found a solution with javascript according to the standards mentioned [here][1].**its not regex.**if you are using this solution there are three things to take care
validation can be used inside the UK
space cant be added. you need to type in your number without spaces
number has to begin with zero
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script >
var name=window.prompt("Enter cell number");
var sixformat=["013397","013398","013873","015242","015394","015395","015396","016973","016974","017683","017684","017687","019467","019755","019756"];
var twoformat=["01","02","03","05","07","08","09"];
sixdi=name.substring(0,6);
twodi=name.substring(0,2);
document.write("phone number:",name,"<br>");
document.write("phone-number length:",name.length);
if(sixformat.includes(sixdi)&&name.length==11)
{
document.write("<br><h1>valid</h1>");
}
else if(sixdi=="016977"&&name.length==10)
{
document.write("<br><h1>valid<h1>");
}
else if(twoformat.includes(twodi)&&(name.length==11))//011########
{
document.write("<br><h1>valid</h1>");
}
else if(twodi=="01"&&(name.length==10))
{
document.write("<br><h1>valid</h1>");
}
else if(name.substring(0,4)=="0800"&&(name.length==10))
{
document.write("<br><h1>Valid</h1></br>");
}
else
{
document.write("<h1>invalid</h1>");
}
</script>
</body>
</html>