i have a phone number in following format +923334173333 and now i want to validate this number exactly in the given format and length with php
Fastest way would be
function validatePhoneNumber($n)
{
return strlen($n) == 13 && $n[0] == '+' && ctype_digit(substr($n, 1)) == 13;
}
validatePhoneNumber('+923334173333'); // returns true
You would need the rules for all possible types of phone numbers and their limitation in the whole world. I'm uncertain if such list even exists.
You can test the length with strlen(), and use ctype_digit() in combination with substr() to check that the substring starting after the '+' consists only of digits.
Related
I was searching for a regex which matches my requirement. But I couldn't find an exact one .
My requirement is
Add validation check to avoid Phone numbers with:
1) 6 digits equal (e.g. 000000 ; 111111)
2) sequence numbers (7 digits) (e.g.
1234567 ; 7654321)
I tried and got this piece of code finally
if (preg_match('/(\d)\1{5}/', $phone)) {
echo "Invalid Phone number";
}
But it matches only the first case. Hope some one will help me. Thanks in advance!
This is one of those times that I'd break away from regex.
This will perform your expected validation (and includes "around-the-clock" number sequences).
PHP Demo
$phone='000000';
$len=strlen($phone);
$rnd_the_clk='0123456789012345';
if(($len==6 && $phone==str_repeat($phone[0],6)) // length is 6, check only one integer used
||
($len==7 && (strpos($rnd_the_clk,$phone)!==false || strpos($rnd_the_clk,strrev($phone))!==false))){ // length is 7, check sequential
echo "invalid";
}else{
echo "valid";
}
I'm trying to match a specific datetime format in PHP's regex:
dd-mm-YYYY HH:ii:ss
It should always be in that format. Meaning that for example when it is the first day of the month there must be a leading zero. E.g.:
01-01-2013 01:01:01
I tried it with the following pattern:
^[0-12]{2}-[0-31]{2}-[0-9]{4} [0-23]{2}:[0-59]{2}:[0-59]{2}$
But the above pattern fails on timestamps like: 09-05-2013 19:45:10.
http://rubular.com/r/eGBAhwiNCR
I understand this may not be the correct approach to validate a date time like this, but I really want to know what is wrong with the above.
[0-12]{2} matches not the numbers 0 till 12. Instead it's a character class allowing 0 to 1 and also the number 2. The subsequent quantifier just allows the repetition of those, meanding 0,1 or 2 repeated two times.
Your other placeholders follow the same non-functioning scheme.
It's best to resort to \d{2} or \d{4} if you can't google a better regex. Even better yet, just use DateTime to verify the format.
The problem is when you are checking the "ranges", for example [0-12] at the beginning. That is a character class, and it is telling the regex to match 0 through 1, and then 2. So if you added more numbers in after the 1st one, it isn't working as you are expecting. Changing your regex slightly (focused on the [0-12] initial), [0-319]{2}-[0-12]{2}-[0-9]{4} [0-23]{2}:[0-59]{2}:[0-59]{2}$, would match 09-01-2011 11:11:10.
Ensuring there are valid numbers for each of those spaces requires a little thinking outside the box. The regex:
(0[1-9]|[12][\d]|3[0-2])-(0[1-9]|1[0-2])-[\d]{4} (0[1-9]|1[\d]|2[0-3]):(0[1-9]|[1-5][\d]):(0[1-9]|[1-5][\d])$
will work for what you are expecting with the regex you attempted.
If you break it down into smaller pieces it makes sense (it looks really scary at the beginning). Looking at the first piece (0-31 for "days").
(0[1-9]|[12][\d]|3[0-2])
This is using an or to handle 3 different cases.
0[1-9] - a zero followed by any number between 1-9. We don't want [0-9]{2} since that will allow numbers like 00. So a number is valid if it starts with 0 and has any other number after it (for single digit days).
[12][\d] - a 1 or 2 followed by any digit. This allows the numbers 10-29 to be valid.
3[0-2] - a 3 followed by anything 0 through 2 matching 30, 31, and 32.
Broken down, it's not too bad but this pattern is then carried out for each "field" in your date. So this regex validates on each field being valid... but a better way to confirm valid dates maybe needed. This doesn't get into the complexity of checking if you can have 30-02 for example, where February doesn't have 30 days.
^[0-9]{2}-[0-9]{2}-[0-9]{4} [0-9]{2}:[0-9]{2}:[0-9]{2}$
The example of validation is in php but the regex is standard
/*pass the date you wanna validate as parameter to the function.
The function returns true if it is valid and false if the date passed is not valid
*/
function DateValid($date){
//format will be fr if the date is in french format and en if the date is in en format
$format='';
//regex that tests if the date is in french format or english, if not in one of these two then it is not valid
if(preg_match("#^(\d{1,2})[\-./ ](\d{1,2})[\-./ ](\d{4})(?: (\d{1,2})(?:[ .-](\d{1,2})){1,2})?$#",$date,$m)){
$format='fr';
}elseif (preg_match('#^(\d{4})[-. ](\d{1,2})[-. ](\d{1,2})(?: (\d{1,2})(?:[ .-](\d{1,2})){1,2})?$#', $date, $m)) {
$format='en';
}else{
echo '<p style="font-size:150px">not english nor french</p>';
return false;
}
//If it is french format or English then check if the date is correct
if($format=='fr'){
if (checkdate($m[2], $m[1], $m[3]) == false || $m[4] >= 24 || $m[5] >= 60 || $m[6] >= 60) {
echo '<p style="font-size:150px">Not valid french</p>';
return false;
}else{
echo '<p style="font-size:150px">Valid french</p>';
return true;
}
}elseif($format=='en'){
if (checkdate($m[2], $m[3], $m[1]) == false || $m[4] >= 24 || $m[5] >= 60 || $m[6] >= 60) {
echo '<p style="font-size:150px">Not valid english</p>';
return false;
}else{
echo '<p style="font-size:150px">Valid english</p>';
return true;
}
}
}
function sendSms($toPhone,$message){
$toPhone=intval(trim($toPhone));
if(strlen($toPhone)== 8 && $toPhone{0}==9){
//sending sms
}else{
return "error";
}
}
I am trying to validate mobile numbers for sending SMS. The first line trims the phone number string and then converts it to an integer. In the if statement, I want to make sure that the number length is 8 digits and it begins with 9. This function always goes for the else even if the number is correct( 8 digits and begins with 9). What could be the issue here.
Why not regex?
$valid = preg_match('/^9[0-9]{7}$/', trim($phone));
You can remove from $toPhone all not digits
function sendSms($toPhone,$message){
$_phone = '';
for ($i = 0; $i < strlen($toPhone); $i++)
{
if (is_numeric($toPhone[$i]))
$_phone .= $toPhone[$i];
}
if(strlen($_phone)== 8 && $_phone[0]=='9'){
//sending sms
}else{
return "error";
}
}
After you converted the phone number to an integer with $toPhone=intval(trim($toPhone));,, you can't access the digits in the way you are trying with $toPhone{0}, because you operate on a number and not on a string any more.
See this isolated example:
$number = 987654321;
var_dump($number{0}); //NULL
However, substr would be capable of doing this:
$number = 987654321;
var_dump(substr($number, 0, 1)); //string(1) "9"
Converting a whole number to integer isn't a good idea anyways, because users might enter the number with spaces in between or signs like + and /. Better search for an already existing approach to validate phone numbers.
Take a look here, where the topic "validate mobile phone numbers" is covered in more detail: A comprehensive regex for phone number validation
You convert variable to integer and apparently $toPhone[0] works on strings only.
The same function without intval() works as you wanted.
function sendSms($toPhone, $message)
{
$toPhone = trim($toPhone);
if(strlen($toPhone) == 8 && $toPhone[0] == 9){
//sending sms
} else {
return "error";
}
}
I'm trying to validate a number by it's length. This number has to have 4 digits so it passes the validation. The problem is when this number has 0's to it's left, like 0035.
Right now I'm at this:
echo (strlen ((string) 0025 ));
Which gives a total of 2, but I want this to count the 0's to it's left, so it gives me a total of 4.
Clearly the cast of the integer to string is not working, how can i do this?
You can't do that way, a left zero means the number is octal and not decimal, you can use sprintf() to do that.
Example:
echo strlen(sprintf("%04d", 25));
Live Test:
http://codepad.viper-7.com/VQr7Xz
Comment Answer:
I don't want to add the 0s to the number, i want to detect if the
number has 0s. If the number received is 25, it's not a valid number.
If it is 0025 it is valid. What i want is to validate only numbers
with 4 digits. – Cláudio Ribeiro
Cláudio, numbers have infinite left zeros, although a user has explicitly type 2 or 3 left zeros there are more hidden left zeros, it's a math basic, this is why it's impossible to know how many left zeros the user has typed if you receive an integer variable. If the variable has a constant size and you want to know how many left zeros it has you can do this:
<?php
$int = 25;
echo 4 - strlen($int);
Live test: http://codepad.viper-7.com/fT2jSn
But if you the variable has variable length it must be a string type instead of a numeric type.
An example where the variable received is a string:
<?php
$strs = array("0025","000035","01","2");
foreach($strs as $str)
{
preg_match("/^0+/", $str, $matches);
echo strlen(#$matches[0]);
echo "<br>";
}
Live Test: http://codepad.viper-7.com/BTRTgR
That should work:
$str = "0025";
if( is_numeric($str) && strlen($str) == 4)
{
echo "pass";
}
If it's a number, not a string, the number doesn't have digits. It has a value. You can format that value into a string with 4 digits which is left padded with 0s. But to validate whether a number has 4 digits is nonsense, since the number value has no formatting. The value only becomes "4 digits" when you format it as base 10 number. Until then the value is a value which can be expressed in a multitude of bases and has a different number of "digits" in all of them.
You either want to format the number to a 0-padded 4 digit string, or you want to check whether the value is between 0 and 9999 (or 1000 and 9999 if it has to be exactly "4 digits").
if (0 <= $num && $num <= 9999) {
$numStr = sprintf('%04d', $num);
} else {
trigger_error('Number out of range');
}
How can I separate a number and get the first two digits in PHP?
For example: 1345 -> I want this output=> 13 or 1542 I want 15.
one possibility would be to use substr:
echo substr($mynumber, 0, 2);
EDIT:
please not that, like hakre said, this will break for negative numbers or small numbers with decimal places. his solution is the better one, as he's doing some checks to avoid this.
First of all you need to normalize your number, because not all numbers in PHP consist of digits only. You might be looking for an integer number:
$number = (int) $number;
Problems you can run in here is the range of integer numbers in PHP or rounding issues, see Integers Docs, INF comes to mind as well.
As the number now is an integer, you can use it in string context and extract the first two characters which will be the first two digits if the number is not negative. If the number is negative, the sign needs to be preserved:
$twoDigits = substr($number, 0, $number < 0 ? 3 : 2);
See the Demo.
Shouldn't be too hard? A simple substring should do the trick (you can treat numbers as strings in a loosely typed language like PHP).
See the PHP manual page for the substr() function.
Something like this:
$output = substr($input, 0, 2); //get first two characters (digits)
You can get the string value of your number then get the part you want using
substr.
this should do what you want
$length = 2;
$newstr = substr($string, $lenght);
With strong type-hinting in new version of PHP (> PHP 7.3) you can't use substr on a function if you have integer or float. Yes, you can cast as string but it's not a good solution.
You can divide by some ten factor and recast to int.
$number = 1345;
$mynumber = (int)($number/100);
echo $mynumber;
Display: 13
If you don't want to use substr you can divide your number by 10 until it has 2 digits:
<?php
function foo($i) {
$i = abs((int)$i);
while ($i > 99)
$i = $i / 10;
return $i;
}
will give you first two digits