Regex for 10-13 digit (international) phone numbers - php

I need to deliver (international) phone numbers from a PHP registration form to an external party. The external party has the following rules for phone numbers.
10-13 digits
dashes are allowed
This means the following numbers are correct
0046701234567 (Swedish)
604-555-5555
5675555555
What would be the best (and most correct) regex to regulate and check all the phone numbers so I can store them in a global database to send them to the external party afterwards?

Just try with:
$input = '604-555-5555';
if (preg_match('/^\d{10,13}$/', str_replace('-', '', $input))) {
// valid
}

<?php
$input = '604-555-5555';
if (preg_match('/[\d-]{10,13}+/', $input, $r) ) {
// valid
foreach($r as $e){echo $e;}do formatting
}
?>

Related

Need a PHP Regex for validation of mobile numbers and address fields

I need a regular expression for validation the mobile number and address field, but input is from PSV file (pipe-sign separated values) i.e.
XXXXXXXX|XXXXXXXXXXXXXXXXXXXX|XXXXXXXXXXXXXXXXXXXX|XXXXXXXXXXXXXX|XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX|XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX|XXXXXXXXXXXXXXXXXXXX|XXXXXXXXXXXXXXXXXXXX|XXXXXXXXXXXXXXXXXXXX|XXXXXXXXXXXXXXXXXXXX|XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX|XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX|XXXXXXXXXXXXXXXXX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XXXXXXXXXXXXXXXXXXXXXXX|XXXXXXXXXXXXXXXXXXXX||
this input is converted in this format:
86082522|801213075672|NRIC|013333344444|SYED ZEESHAN||0107777777|0000000000|||||NO 3046|ROAD 12 MK.7$14000$,HEALE,PNG$PNG$||SHAID ABAD PAKPATAN|KALA|URB5467||8827|20151029|29/10/2015|28/12/2015|113.1000||BHALWAPUR RAWAPALNI KKOTA BANU|||
now this input is okay and valid but if some user forgot to add the mobile address field and address field than it should be not allowed to save in database, now im going to example of invalid mobile number field
86082522|801213075672|NRIC|013333344444|SYED ZEESHAN||8##-777777|0000000000|||||NO 3046|ROAD 12 MK.7$14000$,HEALE,PNG$PNG$||SHAID ABAD PAKPATAN|KALA|URB5467||8827|20151029|29/10/2015|28/12/2015|113.1000||BHALWAPUR RAWAPALNI KKOTA BANU|||
now above example is invalid mobile number, because its containing the some charcters as well. so i need a regex that can remove these charcters.
Okay how about this.
$string = '86082522|801213075672|NRIC|013333344444|SYED ZEESHAN||0111123444443|0000000000|||||NO 3046|ROAD 12 MK.7$14000$,HEALE,PNG$PNG$||SHAID ABAD PAKPATAN|KALA|URB5467||8827|20151029|29/10/2015|28/12/2015|113.1000||BHALWAPUR RAWAPALNI KKOTA BANU|||';
$array = explode('|', $string);
if(preg_match('/^0\d{9,14}$/', $array[6])) {
echo 'true';
} else {
echo 'false';
}
Regex101 demo: https://regex101.com/r/iN5oT5/1
We require the string start with a 0 then have 9-14 ({9,14}) additional numbers (\d).

How to validate phone numbers using php without regexp?

I want to validate users phone numbers when they register in my website. I use this code to do this :
$mobile = mysql_real_escape_string($_POST['mobile']);
//check mobile validity
$options = array('options' => array('min_range' => 0));
if(filter_var($mobile, FILTER_VALIDATE_INT, $options) == FALSE)
{
$_SESSION['warnings']['warning_mobile'] = ENTER_VALID_MOBILE;
}
else
{
$_SESSION['warnings']['warning_mobile'] = '';
$_SESSION['temp_post']['mobile'] = $mobile;
}
As you can see the code check if this number contains valid int digits and if it is everything going ok if not it give me error message .
My problem is : This code does not accept numbers which starts with zero for example (0 555 555 5555 this is invalid number).
Is there a way to allow this code to accept this numbers starting with zero??
Leaving on a side the fact that with a regular expression you could solve this problem easily, there are a couple of things to consider:
$mobile is a string: filter_var($mobile, FILTER_VALIDATE_INT)
will allways return false.
do you want to consider digits only or you need to support numbers containing characters such as spaces, hyphen and plus? e.g. "+1 23-4555-555"
If you need to support "plain numeric" only, take a look to is_numeric. It checks if a variable is a number or a string made only by digits.
About your question:
Is there a way to allow this code to accept this numbers starting with
zero??
Your code doesn't work because $mobile is not an integer, and not because your number starts with 0.
The final suggestion still is to use a regexes, which are the optimal solution for this kind of problems.

Extract numbers from phone number input field (PHP)

I've got a phone number input field, which allows a user to add a phone number in whatever format they want (555-555-5555, (555) 555 - 5555, etc).
Since it a phone number field only, I can ignore everything but the numbers in the field.
I'm currently using the following code. It extracts all the numbers, but the issue is that they are not in order - it's in a jumbled order.
How do I extract the numbers in the order that they appear in the original string?
preg_match_all('/\d+/', $Phone, $matches);
$Phone = implode('', $matches[0]);
Edit: They are actually not in a jumbled order from this function - I was inserting the numbers into a int(10) database field, which caused the jumbling. But, the answers below are still a more efficient way of accomplishing my goal.
Use preg_replace to remove any non-digits:
$numbers = preg_replace('/[^\d]/','',$Phone);
Note: '[^\d]' can be replaced with '\D' (safe in non-unicode mode).
$Phone = preg_replace('/[^\d]/', '', $Phone);
Why not just replace everything in the string that is not a digit?
$number = preg_replace("/[^0-9]/", '', $Phone);
Try it
if (!preg_match("/^[0-9\-]*$/",$Phone)) {
echo "Only Numeric and strip (-)";
}
Example:
Good: 0877-9320-9356
Failed: 0877 9320 9356 or 087793209356

Validating special form of IP address

I have encountered a strange IP which has redundant zero values among the octets. Is there anyway to properly validate this as an IP or use regular expression to remove those redundant zeroes?
example is of follows:
218.064.215.239 (take note of the extra zero at the second octet "064").
I do have one working IP validation function but it will not validiate this Ip properly due to the nature of the regular expression unable to accept that extra zero. Following is the code in PHP:
function valid_ip($ip) {
return preg_match("/^([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])" .
"(\.([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}$/", $ip);
}
thanks for any help in advance peeps! :D
This will correct them:
$ip = "123.456.007.89";
$octets = explode(".", $ip);
$corrected = array();
foreach ($octets as $octet) {
array_push($corrected, (int)$octet);
}
echo implode(".", $corrected);
You have to accept the zero like this:
^(0?[1-9]|0?[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\.(0?[0-9]|0?[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}$
Play with this regular expression on rubular.com.
The 0? I added matches zero or one occurence of 0. So 0?[1-9][0-9] for example matches both 010 and 10 for example.
Change the bare |1 occurrences to |[01]. Are you sure this is not supposed to be interpreted as an octal number, though? Some resolvers do that.
Use ip2long().
You should figure out where those extra zeroes are coming from. Those leading zeroes can't be just dropped. On most platforms they mean that the octet is in octal form instead of decimal. That is: 064 octal equals 52 decimal.
Did you have a go yourself? It's really quite simple.
|1[0-9][0-9]| matches 100-199, as you are now wanting to match 000-199 (as above that it is 200-155) you just need to make a set for the 1 to be 1 or 0.
function valid_ip($ip) {
return preg_match("/^([1-9]|[1-9][0-9]|[01][0-9][0-9]|2[0-4][0-9]|25[0-5])".
"(\.([0-9]|[1-9][0-9]|[01][0-9][0-9]|2[0-4][0-9]|25[0-5])){3}$/", $ip);
}
And that can be refactored down (allowing leading zeroes) to:
function valid_ip($ip) {
return preg_match("/^([01]?[0-9]{1,2}|2[0-4][0-9]|25[0-5])".
"(\.([01]?[0-9]{1,2}|2[0-4][0-9]|25[0-5])){3}$/", $ip);
}
Or to strip these unneeded zeros:
function strip_ip($ip) {
return preg_replace( '/0+([^0])(\.|$)/' , '$1$2' , $ip );
}

Using regex to fix phone numbers in a CSV with PHP

My new phone does not recognize a phone number unless its area code matches the incoming call. Since I live in Idaho where an area code is not needed for in-state calls, many of my contacts were saved without an area code. Since I have thousands of contacts stored in my phone, it would not be practical to manually update them. I decided to write the following PHP script to handle the problem. It seems to work well, except that I'm finding duplicate area codes at the beginning of random contacts.
<?php
//the script can take a while to complete
set_time_limit(200);
function validate_area_code($number) {
//digits are taken one by one out of $number, and insert in to $numString
$numString = "";
for ($i = 0; $i < strlen($number); $i++) {
$curr = substr($number,$i,1);
//only copy from $number to $numString when the character is numeric
if (is_numeric($curr)) {
$numString = $numString . $curr;
}
}
//add area code "208" to the beginning of any phone number of length 7
if (strlen($numString) == 7) {
return "208" . $numString;
//remove country code (none of the contacts are outside the U.S.)
} else if (strlen($numString) == 11) {
return preg_replace("/^1/","",$numString);
} else {
return $numString;
}
}
//matches any phone number in the csv
$pattern = "/((1? ?\(?[2-9]\d\d\)? *)? ?\d\d\d-?\d\d\d\d)/";
$csv = file_get_contents("contacts2.CSV");
preg_match_all($pattern,$csv,$matches);
foreach ($matches[0] as $key1 => $value) {
/*create a pattern that matches the specific phone number by adding slashes before possible special characters*/
$pattern = preg_replace("/\(|\)|\-/","\\\\$0",$value);
//create the replacement phone number
$replacement = validate_area_code($value);
//add delimeters
$pattern = "/" . $pattern . "/";
$csv = preg_replace($pattern,$replacement,$csv);
}
echo $csv;
?>
Is there a better approach to modifying the CSV? Also, is there a way to minimize the number of passes over the CSV? In the script above, preg_replace is called thousands of times on a very large String.
If I understand you correctly, you just need to prepend the area code to any 7-digit phone number anywhere in this file, right? I have no idea what kind of system you're on, but if you have some decent tools, here are a couple options. And of course, the approaches they take can presumably be implemented in PHP; that's just not one of my languages.
So, how about a sed one-liner? Just look for 7-digit phone numbers, bounded by either beginning of line or comma on the left, and comma or end of line on the right.
sed -r 's/(^|,)([0-9]{3}-[0-9]{4})(,|$)/\1208-\2\3/g' contacts.csv
Or if you want to only apply it to certain fields, perl (or awk) would be easier. Suppose it's the second field:
perl -F, -ane '$"=","; $F[1]=~s/^[0-9]{3}-[0-9]{4}$/208-$&/; print "#F";' contacts.csv
The -F, indicates the field separator, the $" is the output field separator (yes, it gets assigned once per loop, oh well), the arrays are zero-indexed so second field is $F[1], there's a run-of-the-mill substitution, and you print the results.
Ah programs... sometimes a 10-min hack is better.
If it were me... I'd import the CSV into Excel, sort it by something - maybe the length of the phone number or something. Make a new col for the fixed phone number. When you have a group of similarly-fouled numbers, make a formula to fix. Same for the next group. Should be pretty quick, no? Then export to .csv again, omitting the bad col.
A little more digging on my own revealed the issues with the regex in my question. The problem is with duplicate contacts in the csv.
Example:
(208) 555-5555, 555-5555
After the first pass becomes:
2085555555, 208555555
and After the second pass becomes
2082085555555, 2082085555555
I worked around this by changing the replacement regex to:
//add escapes for special characters
$pattern = preg_replace("/\(|\)|\-|\./","\\\\$0",$value);
//add delimiters, and optional area code
$pattern = "/(\(?[0-9]{3}\)?)? ?" . $pattern . "/";

Categories