Regex matching a date and time - php

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;
}
}
}

Related

how to check that a number is a mobile number of a user in pakistan and not a landline number

What i have done is remove the +92 or 0092 from the start and used the following code to check if it is a valid mobile number for a pakistani person
if(preg_match('/3[0-4][0-9](?:.*)/', $number) == 1) {
//Pakistani mobile number
} else {
// not a pakistani mobile number
}
is this approach right?
Based on the description found on wikipedia: Telephone_numbers_in_Pakistan,
then something like this pattern:
^0?3(?:[0-46]\d|55)\d{7}$
Or without considering the special case of operator 5 (SCO):
^0?3[0-6]\d{8}$
Or with including the country prefix as an optional group:
^((?:00|\+)92)?(0?3(?:[0-46]\d|55)\d{7})$
Php Test Snippet:
<?php
$telnumber='03441234567';
if(preg_match('/^((?:00|\+)92)?(0?3(?:[0-46]\d|55)\d{7})$/', $telnumber))
{
echo "matches pattern";
} else
{
echo "doesn't match pattern";
}
(^\+92[0-9]{10}$)|(^\0092[0-9]{10}$)
Here string append +92 initially then check next 10 digit or if there is 0092 in front of number then it consists of 10 digit number.
The +92 and 0092 check your ISD code initially not other.
For only accept \d{4} and 9 digit ^((0)(3))([0-9]{9})$
Pakistan mobile number examples:
+923331234567
00923331234567
03331234567
try this regex:
"^((?:00|\\+)92)?(0?3(?:[0-4])\\d{7})\$"
((?:00|\\+)92)? -> 0092 or +92 or none
0?3 -> 03 or 3
(?:[0-4]) -> after above string only 0,1,2,3,4 can be accepted (e.g. 031, 032, 033, 034)
\\d{7} -> length 7 characters will be accepted after above string
Note: other country regex can be made from these examples easily
Use the following python code to validate Pakistani Phone Number. It checks country code (+92, 0092, 92, 0) followed by a 3 and then for carrier code of 2 digits with limit of first digit (0 - 4) and limit of second digit (0 - 9) and at the end 7 digits in range (0 - 9).
import re
def validate_not_mobile(value):
pat = re.compile(r'(^((\+92)?(0092)?(92)?(0)?)(3)([0-4]{1})([0-9]{1})([0-9]{7})$)')
if re.fullmatch(pat, value):
print(f"'{value}' is a valid number!")
else:
print(f"'{value}' is NOT a valid number!")
I have tested the code with several test numbers and it has worked fine. If there is any further update I'll update it here.

Regex to avoid equal and sequence digits

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";
}

How to validate time string in hh:mm using preg match?

Below are the following possiblities. Time is for 12 hours
Inputs Output should as
"05:30" True
"asasds" FALSE
"05:30:sads" FALSE
"ADAS:05:40" FALSE
"04:30:40" FALSE
Below is the code that I wrote,
$value = "05:30" ;
if(!preg_match("/(1[012]|0[0-9]):([0-5][0-9])/", $value)){
echo "failed"; exit;
}
echo "passed"; exit;
But it prints as passed if I give the $value = "05:30:asdsa". However I need the output to be "failed".
Use anchors to match the start and the end, e.g.
!preg_match("/^(1[012]|0[0-9]):([0-5][0-9])$/", $value)
//^ See here ^
I just coded it for myself some minutes ago. It is basically controlling that is between 00:00 and 23:59
edit
preg_match("/(0?\d|1\d|2[0-3]):[0-5]\d/", $line, $matches_time);
You need to be sure that 25:30 is not valid. 24:00 is not valid but 00:00 is valid.
this code can make it perfect:
$string='00:34';
$pattern='%^([0-1][0-9])|([2][0-3]):[0-5][0-9]$%';
if(preg_match($pattern,$string))
echo '<b>'.$string.'</b> is a valid time in 24 hours format';
If you want to check only 12 hours format, you can use this one:
$string='09:24';
$pattern='%^([0][0-9])|([1][0-2]):[0-5][0-9]$%';
if(preg_match($pattern,$string))
echo '<b>'.$string.'</b> is a valid time in 12 hours format';

Check whether day is specified in a date string

Test case scenario - User clicks on one of two links: 2012/10, or 2012/10/15.
I need to know whether the DAY is specified within the link. I am already stripping the rest of the link (except above) out of my URL, am I am passing the value to an AJAX request to change days on an archive page.
I can do this in either JS or PHP - is checking against the regex /\d{4}\/\d{2}\/\d{2}/ the only approach to seeing if the day was specified or not?
You can also do this if you always get this format: 2012/10 or 2012/10/15
if( str.split("/").length == 3 ) { }
But than there is no guaranty it will be numbers. If you want to be sure they are numbers you do need that kind of regex to match the String.
You could explode the date by the "/" delimiter, then count the items:
$str = "2012/10";
$str2 = "2012/10/5";
echo count(explode("/", $str)); // 2
echo count(explode("/", $str2)); // 3
Or, turn it into a function:
<?php
function getDateParts($date) {
$date = explode("/", $date);
$y = !empty($date[0]) ? $date[0] : date("Y");
$m = !empty($date[1]) ? $date[1] : date("m");
$d = !empty($date[2]) ? $date[2] : date("d");
return array($y, $m, $d);
}
?>
I would personally use a regex, it is a great way of testing this sort of thing. Alternatively, you can split/implode the string on /, you will have an array of 3 strings (hopefully) which you can then test. I'd probably use that technique if I was going to do work with it later.
The easiest and fastest way is to check the length of the string!
In fact, you need to distinguish between: yyyy/mm/dd (which is 10 characters long) and yyyy/mm (which is 7 characters).
if(strlen($str) > 7) {
// Contains day
}
else {
// Does not contain day
}
This will work EVEN if you do not use leading zeros!
In fact:
2013/7/6 -> 8 characters (> 7 -> success)
2013/7 -> 6 characters (< 7 -> success)
This is certainly the fastest code too, as it does not require PHP to iterate over the whole string (as using explode() does).

how can i verify phone number with php

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.

Categories