How to validate phone number using PHP? [duplicate] - php

This question already has answers here:
How to validate phone numbers using regex
(43 answers)
Closed 9 years ago.
How to validate phone number using php

Here's how I find valid 10-digit US phone numbers. At this point I'm assuming the user wants my content so the numbers themselves are trusted. I'm using in an app that ultimately sends an SMS message so I just want the raw numbers no matter what. Formatting can always be added later
//eliminate every char except 0-9
$justNums = preg_replace("/[^0-9]/", '', $string);
//eliminate leading 1 if its there
if (strlen($justNums) == 11) $justNums = preg_replace("/^1/", '',$justNums);
//if we have 10 digits left, it's probably valid.
if (strlen($justNums) == 10) $isPhoneNum = true;
Edit: I ended up having to port this to Java, if anyone's interested. It runs on every keystroke so I tried to keep it fairly light:
boolean isPhoneNum = false;
if (str.length() >= 10 && str.length() <= 14 ) {
//14: (###) ###-####
//eliminate every char except 0-9
str = str.replaceAll("[^0-9]", "");
//remove leading 1 if it's there
if (str.length() == 11) str = str.replaceAll("^1", "");
isPhoneNum = str.length() == 10;
}
Log.d("ISPHONENUM", String.valueOf(isPhoneNum));

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
}

I depends heavily on which number formats you aim to support, and how strict you want to enforce number grouping, use of whitespace and other separators etc....
Take a look at this similar question to get some ideas.
Then there is E.164 which is a numbering standard recommendation from ITU-T

Related

Password parameters using preg_match [duplicate]

This question already has an answer here:
Reference - Password Validation
(1 answer)
Closed 5 years ago.
I am trying to establish password parameters to be 8-20 characters long, at least one upper case character, number, and symbol. I have written the code as such
(preg_match ('/^(\W+)(\d+)([A-Z]+)([a-z]+){8,20}$/', $_POST['pass1']) )
My interpretation of my code is as follows:
W+ one or more symbols (non alpha numeric)
d+ one or more numbers
[A-Z]+ one or more uppercase characters
[a-z]+ one or more lower case characters
{8,20} string length min 8 max 20
When I enter the password as Anyhelp4me! I get an invalid password message. What are your suggestions.
Don't do it all with one regex. It will be far more maintainable, understandable, and easier to change in the future if you make multiple calls to preg_match with multiple regexes.
$password_is_ok =
preg_match( '/\W/', $pass ) &&
preg_match( '/\d/', $pass ) &&
preg_match( '/[a-z]/', $pass ) &&
preg_match( '/[A-Z]/', $pass ) &&
strlen( $pass ) >= 8 &&
strlen( $pass ) <= 20;
That is far more readable and understandable by the next person who has to read your code (who might be you) than any single-regex monstrosity you can concoct.
Okay...I tried the previous recommendation and it only imposed the "8,10" restriction. I found this on stackoverflow "Create preg_match for password validation allowing (!##$%)" and modified the code presented in that response as follows:
/^(?=.*\d)(?=.*[A-Z])(?=.*[a-z])(?=.*\W)[0-9A-Za-z!##$%]{8,20}$/
I have tested it several times and it does work. You have to have at least one digit, one uppercase, one lower case and a specified symbol (!##$%) and between 8 and 20 characters.

How to ensure user submitted numeric input follows a certain format

I am working in PHP and I want to check if a given user submitted numeric input is not too big or too small.
I am storing the amounts in the database as 64 bit integers (multiply them by 10^8 to avoid rounding errors in future calculations). I am limiting the amounts so that they cannot exceed the following precision: no more than 4 numbers after the decimal point. Also since the upper limit on user input should be 99 million, I also want to specify no more than 8 numbers precending the decimal point. How can I achieve this neatly?
My current approach seems a bit hack-ish:
Code:
//Check for existence of decimal point in string using strpos
//explode the string by the decimal point
//do a strlen on both the strings and check they dont exceed 8 and 4 respectively
//if no decimal point, simply do a strelen and check it's not greater than 8
Also, I don't want the inputted data to be smaller than 0.0001. I am proficient in php for web design not familiar with the math functions of php is there an easy way to handle this?
Thanks for any tips
Using the code below you can check whether the $input conforms to your requirements.
(See also this short demo.)
$input = ...;
$pattern = "~^\s*\d{1,8}(?:\.\d{1,4})?\s*$~";
if (($input > 0) && preg_match($pattern, $input)) {
/* $input is OK */
} else {
/* $input is NOT OK */
}
Requirements:
$input has an integral part that is between 1 and 8 digits long.
$input optionally contains a . followed by 1 to 4 digits (fractional part).
$input is a positive number greater than or equal to 0.0001.
You can use regular expressions and the mb_ereg_match(regex,string) function
you can try this:
if (preg_match('~^(?>[1-9]\d{0,7}+|0)(?>\.\d{0,3}+[1,9])?$~', trim($number), $result))
// true
else
// false
This pattern avoids things like 00015 or 1.000, but if you want to allow this, just replace [1-9] by \d or better use ~^\d{1,8}+(?>\.\d{1,4}+)?$~ instead.
You must work after with $result which contain the trimed and verified number.
I think the following regex will match your needs.
It will match all numbers between 99999999.9999 and 00000000.0000 with and without the decimal point and also empty string.
The fractal part contains no more than 4 digits
if (preg_match('~^[0..9]{0,8}(?:\.[0..9]{1,4})?$~'), $number) {
$match = TRUE;
} else{
$match = FALSE;
}
See if this works:
$number = '123.4567';
if(preg_match('/^\s*\d*\.?\d{4}\s*$/', $number)) echo "Match";
else echo "Not match";

Validating International Phone Numbers in PHP [duplicate]

This question already has answers here:
How to validate phone numbers using regex
(43 answers)
Closed 4 years ago.
I've been searching for hours to find a regex that does this for me, all the ones I've found either require dashes or limit something else that I don't need.
Like this one:
^(?([0-9]{3}))?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$
Basically I want to allow these types of input for phone number, these are all valid:
+000 111111111
+00011111111111
0022 111111111111
0022111111111
+333-4444-5555-6666
000-7878787-0000-4587
Note that the number of digits is not limited, I only want the validation to filter out empty inputs and the alphabet. Also filter out all other characters except a maximum of 4 dashes, max. 4 spaces and an optional single plus sign.
Is this possible through preg_match or not?
Any help is appreciated, thanks!
Sure its possible. But to my opinion dangerous to use stuff that is not understood. I would do something like this
^(?!(?:\d*-){5,})(?!(?:\d* ){5,})\+?[\d- ]+$
See it here on Regexr
The last part \+?[\d- ]+ allows an optional + followed by at least one digit, dash or space
The negative lookaheads ensure that there are not more than 4 dash or spaces.
Limitations:
- The dash or space can be in one row
- it accepts also - as valid
Try it yourself on the Regexr link, you can just add examples what you want.
Strip wanted characters out (" ", "-"), count the amount then chuck an if statement if count <= 4 (for the "+" character it would be == 1). So in total it would be
if (countSpace <= 4 && countDash <= 4 && countPlus == 1) {
...
}
As for being empty, just use the standard form validation for checking if the input has been filled or not.

Determine if 10 digit string is valid Amazon ASIN

I have a 10 digit string being passed to me, and I want to verify that it is a valid ASIN before doing more processing and/or redirection.
I know that a non ISBN ASIN will always be non-numeric and 10 characters in length
I just want to be able to tell if the item being passed is a valid ASIN or is it just a search string after I have already eliminated that it could be a ISBN.
For example "SOUNDBOARD" is a search term while "B000J5XS3C" is an ASIN and "1412775884" is an ISBN.
Is there a lightweight way to check ASIN?
Update, 2017
#Leonid commented that he’s found the ASIN BT00LLINKI.
Although ASIN’s don’t seem to be strictly incremental, the oldest non-ISBN ASINs do tend to have more zeros than newer ASINs. Perhaps it was inevitable that we’d start seeing ASINs with no zero padding (and then what, I wonder...). So we’re now looking for "B" followed by nine alphanumeric characters (or an ISBN) — unfortunately, the "loss" of that zero makes it a lot easier to get a false positive.
/^(B[\dA-Z]{9}|\d{9}(X|\d))$/
Original answer
In Javascript, I use the following regexp to determine whether a string is or includes what’s plausibly an ASIN:
/^\s*(B\d{2}[A-Z\d]{7}|\d{9}[X\d])\s*$/
or, without worrying about extra whitespace or capturing:
/^(B\d{2}[A-Z\d]{7}|\d{9}[X\d])$/
As others have mentioned, Amazon hasn't really revealed the spec. In practice I've only seen two possible formats for ASINs, though:
10-digit ISBNs, which are 9 digits + a final character which may be a digit or "X".
The letter B followed by two digits followed by seven ASCII-range alphanumeric characters (with alpha chars being uppercase).
If anyone has encountered an ASIN that doesn't fit that pattern, chime in. It may actually be possible to get more restrictive than this, but I'm not certain. Non-ISBN ASINs might only use a subset of alphabetic characters, but even if so, they do use most of them. Some seem to appear more frequently than others, at least (K, Z, Q, W...)
For PHP, there is a valid regular expression for ASINs here.
function isAsin($string){
$ptn = "/B[0-9]{2}[0-9A-Z]{7}|[0-9]{9}(X|0-9])/";
return preg_match($ptn, $string, $matches) === 1;
}
maybe you could check on the amazon site whether the ASIN exists.
http://www.amazon.com/dp/YOUR10DIGITASIN
this URL return a http-statuscode=200 when the product exists and a 404 if that was not a valid ASIN.
After trying couple of solutions (including the top voted answer) they did not work well in PHP. (ex. 8619203011 is shown as ASIN)
Here is the solution that works very well:
function isAsin($string){
$ptn = "/^(?i)(B0|BT)[0-9A-Z]{8}$/";
if (preg_match($ptn, $string, $matches)) {
return true;
}
}
$testAsins = array('k023l5bix8', 'bb03l5bix8', 'b143l5bix8', 'bt00plinki', ' ', '');
foreach ($testAsins as $testAsin) {
if(isAsin($testAsin)){
echo $testAsin." is ASIN"."<br>";
} else {
echo $testAsin." is NOT ASIN"."<br>";
}
}
Explanation:
/^(?i)(B0|BT)[0-9A-Z]{8}$/
/^ = Beginning
(?i) = Case in-sensitive
(B0|BT)= Starting with B0 or BT
[0-9A-Z]= any numbers or letters
{8} = 8 numbers or letters allowed (on top of +2 from B0 or BT)

How do you format a 10 digit string into a phone number?

I have database records in the form of 10 character long strings, such as 4085551234.
I wish to format these into this format: (408) 555-1234.
I think this is regex related. I'm new to programming and completely self-taught here, so any sort of resource relating to performing text processing would be appreciated as well. Thanks!
A regex is definitely overkill for this one. If you wanted to take a "phone number" and normalize it to 10 digits, that would be a good use for a regex. To do what you're asking, just do something like:
echo '('.substr($data, 0, 3).') '.substr($data, 3, 3).'-'.substr($data,6);
Since you already know how to divide up your data, you can just use substr or something similar to grab the parts you want. RegEx is useful for matching strings which don't always have a strict format. (Like variable numbers of spaces, variable stuff before or after it, extra dashes, etc). But in your case the input is always strictly formatted 10 digits, nothing else, so you don't need the extra overhead of a RegEx to format it.
Take a look here: Format phone number
function format_phone($phone)
{
$phone = preg_replace("/^\d/", "", $phone);
if(strlen($phone) == 7)
return preg_replace("/(\d{3})(\d{4})/", "$1-$2", $phone);
elseif(strlen($phone) == 10)
return preg_replace("/(\d{3})(\d{3})(\d{4})/", "($1) $2-$3", $phone);
else
return $phone;
}
I'd probably go with
$num = "4085551234"; // given
$formatted = "(".substr($num,0,3).") ".substr($num,3,3)."-".substr($num,6);
Regex isn't really appropriate here.
Trivially you could do something like:
\(\d\{3\}\)\(\d\{3\}\)\(\d\{4\}\)
To match the 10 digits into 3 subgroup expressions, and then print them out using each subgroup:
"(\1) \2-\3
But in practice free form data is usually a little trickier
I had to do this question for my advanced placement computer science class.
Java:
Write a program that accepts a 10 digit # and formats it as a phone number.
Ex: 705726552
Output: (705)726-2552
import java.util.Scanner;
public class TelNumCorrection{
public static void main(String[]args){
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a 10 digit number");
String num=scan.nextLine();
String a=num.substring(0,3);
String b=num.substring(3,6);
String c=num.substring(6);
System.out.println("("+a+ ")"+b+"-"+c);
}
}

Categories