I am using following regex to validate date in format dd/mm/yyyy in php:
preg_match("/([0-9]{2})\/([0-9]{2})\/([0-9]{4})/", $e_startdate, $matches)
But what will be the regex to validate time in the format 10:20 PM or AM. I want a regex which will validate following format for me.
<number><number><colon><number><number><space><AM or PM>
Thanks
You can use the regex:
(0[0-9]|1[0-2]):[0-5][0-9] [AP]M
The following should validate the format you requested:
preg_match("/(\d{2}):(\d{2}) (AM|PM)/", $e_startdate, $matches);
Note that this is not necessarily a valid time. You could enter stuff like 32:62 AM. You need something like this for time validation:
preg_match("/(0?\d|1[0-2]):(0\d|[0-5]\d) (AM|PM)/i", $e_startdate, $matches);
Mind to match the whole thing case-insensitive (like i did in the second example). Otherwise lowercase am, pm, etc. are not going to work.
Regular Expression:
(([0-1][0-9])|([2][0-3])):([0-5][0-9]):([0-5][0-9])
Validates time in MySQL time format. 24 hour time colon separated hours:minutes:seconds hh:mm:ss
Matches: 09:30:00 | 17:45:20 | 23:59:59
Non-Matches: 24:00:00
/\d{2}:\d{2} (AM|PM)/
I started with elusive's answer, but needed a bit more flexibility. This one makes the minutes optional, as well as the space before AM/PM
/(0?\d|1[0-2])(:(0\d|[0-5]\d))?[ ]?(A|P)M/i
Related
I need to validate a precise date format in php.
In my case the optimum date format should be: e.g. 1/1/2017 (without leading zeros) and the code should allow me to avoid the rest of date's format.
The following code is what i wrote but with no result:
if(preg_match("/([1-9]|[1-2][0-9]|3[0-1]-([1-9]|1[0-2])-^[0-9]{4})$/", $date){
// insert into etc. etc....
}else{
// update etc. etc....
}
The problem is that the code doesn't properly validate the date; it accepts every kind of date format.
I noticed that the OP's submitted answer was not bulletproof, so I started to research some of the functions mentioned in the comments under the question and some of my own thoughts.
I agree with apokryfos in that using regex to validate a date expression is not best practice. A pure regex solution is going to be an increasingly verbose and decreasingly comprehensible pattern because it will have to factor leap years both in the past and future. For this reason, I've investigated a few date functions that php has on offer.
date_parse_from_format() as suggested by Alex Howansky. Unfortunately, it will not be a stand-alone solution for this case because the format parameter obeys the syntax/rules of DateTime::createFromFormat():
See how d and j are grouped together, as are m and n. Consequently, this function will catch invalid dates, but not the unwanted leading zeros.
strptime() as suggested by Casimir et Hippolyte. This function affords matching days without leading zeros using %e. This function does not have a character that matches non-zero-leading month numbers. Furthermore, there can be hiccups with this function bases on the operating system.
check_date() seems like a logical choice, but again it will not flinch at zero-led numbers. Furthermore, this function requires a bit more data preparation than the others, because it requires the month, day, and year values to be individualized.
if(!DateTime::createFromFormat('j/n/Y', $date)) suggested by deceze regarding a slightly different scenario will not work in this case. createFromFormat() will go to great lengths to construct a valid date -- even a string like 99/99/9999 will make it through.
In an attempt to create the most concise expression, here is what I can offer as a seemingly bulletproof solution using a DateTime class:
if (($d=DateTime::createFromFormat('n/j/Y',$date)) && $date==$d->format('n/j/Y')){
// valid
}else{
// invalid
}
strtotime() can be used with a single condition for this case because the OP's date format uses slashes as a delimiter and this function will correctly parse the date expression "American-style".
This seems to be the simplest way to check for a valid date without leading zeros: Demo Link
if(date('n/j/Y',strtotime($date))==$date){
// valid
}else{
// invalid
}
If you are dealing with datetime expressions and don't wish to check the time portion, you can call this line before conditional line:
$date = explode(' ', $date)[0]; // create an array of two elements: date and time, then only access date
Demo Link
or
$date = strstr($date, ' ', true); // extract substring prior to first space
you can use with Carbon
$date->format('j')
Your date delimiter is / and not -, so add \/ to regex for /. And use ^ at the start of regex:
if(preg_match("/^([1-9]|[1-2][0-9]|3[0-1])\/([1-9]|1[0-2])\/([0-9]{4})$/", $date){
After several hours finally i found the correct answer. The correct pattern for php is to use single quote (') and not the double quote (") e.g.:
preg_match('/^([1-9]|[1-2][0-9]|3[0-1])\/([1-9]|1[0-2])\/([0-9]{4})/',$date)
this works fine for me... Thanks everyone especially to #Mohammad Hamedani 'cause the expression was correct but the f******g quote makes me gone crazy
i have a string which is something like
<?php
$string = Monday & SUNDAY 11:30 PM et/pt;
//or
$string = Monday 11:30 PM et/pt;
?>
i want to fetch '11:30 PM' in both the cases for which i guess i cant use explode so what will be the regular expression for this ,,,also please tell me something pretty nice to learn regular expressions.
Thanks in advance
Credit goes to the commenters below for several fixes to the original approach, but there were still some unresolved issues.
If you want a fixed 2 hour format: (0[0-9]|1[0-2]):[0-5]\d [AP]M
to validly match a twelve-our-clock i'd use a regex like below. A twelve-hour-clock goes from 01:00 to 12:59:
$regex = "#\b(?:0[0-9]|1[0-2]):[0-5][0-9] [AP]M\b#i";
Malik, to retrieve time/date you might use premade library regexes, search this query: http://regexlib.com/Search.aspx?k=digit&c=5&m=-1&ps=20
Basically your time fields are similar, (having the same delimiter ':' ), i'd recommend simple regex: \d{1,2}:\d{2} [PA]M to match in the input string. If you want make it case-insensitive use i, pattern modifier.
For the basics of regex welcome to read here.
I give you this match function for PHP (i after second slash (/) makes pattern case-insensitive: am, AM, Am, aM will be equal):
preg_match('/\d{1,2}:\d{2} [PA]M/i', $string, $time);
print ($time);
If there might not be a space after digits (ex. 11:30am) or more then one space char., then the regex should look like this:
/\d{1,2}:\d{2}\s*[PA]M/i
this code will give you 11:30 PM
preg_match('$([0-9:]{3,5}) ([AP])M$','Monday & SUNDAY 11:30 PM et/pt',$m);
echo $m['1']." ".$m['2']."M";
I am trying to extract a date from a string variable and was hoping to get some help.
$editdate = "Content last modified on 17 May 2011 at 23:13";
from this string, I am trying to extract 17 May 2011, please keep in mind that the date will vary and the code needs to be able to extract any date in this format, DD MMM YYYY.
I thought of using preg_match to do this but I couldn't come up with a proper regex pattern that would extract the date properly.
Is this possible to do with regex or should I use a different function?
Thanks for the help !
Try:
$timestamp = strtotime( str_replace( array("Content last modified ", "at"), "", $editdate ) );
Which will leave you with an epoch time stamp that you can then output however you like using date()
This is possible with a regex. Given the format DD MMM YYYY you would need a regex that matches two (or one?) digits, then one space, three letters, one space and four digits.
That would look like:
$regex = '/(\d{2} [a-z]{3} \d{4})/i';
This can be optimized further.
Presuming the textual content of your string is always the same, and that it always ends with the time...
$editdate = substr($editdate, 25, -9); // 17 May 2011
However, this is very inflexible if the date format were ever to change.
Try this 'un:
preg_match('/(\d?\d [A-Za-z]+ \d\d\d\d) at (\d\d\:\d\d)/', $editdate, $matches);
print_r($matches);
$date = $matches[1];
$time = $matches[2];
I THINK that'll work in all cases (though it is pretty ugly).... :)
This might be the pattern that does the trick:
([0-9]){1}([0-9]){0,1}(\s.*\s)([0-9]){4}
Search for 1 digit then there might be another, followed by a space and character, a space and 4 digits for the year.
Can anyone tell me a regex to preg_replace all timestamps from a log file? The format is below. Leading zero's on month and day, not on hour.
05/05 : 5:00 PM or MM/DD : HH:mm AM/PM
The regex to match that is as follows:
/[01][0-9]\/[0-3]?[0-9] : 1?[0-9]:[0-5][0-9] (A|P)M/
The appropriate syntax for preg_replace or the like would depend on how you want the replacement to look.
How can I take a line like this:
Digital Presentation (10:45), (11:30), 12:00, 12:40, 13:20, 14:00, 14:40, 15:20, 16:00, 16:40, 17:20, 18:00, 18:40, 19:20, 20:00, 20:40, 21:20, 22:00, 22:40, 23:10, 23:40.
And match all the 24 hour times so I can convert to a more human readable format using date()?
Also I want to match times in the 24:00-24:59 range too
Thanks!
You could use a regular expression like the following, which allows values from 00:00 through to 24:59 inclusive.
(?:[01][0-9]|2[0-4]):[0-5][0-9]
You seem to know what you're doing, so I'll only give a brief example without converting the times into date strings.
$times = array();
if (preg_match_all('/(?:[01][0-9]|2[0-4]):[0-5][0-9]/', $subject, $matches)) {
$times = $matches[0];
}
print_r($times);
If the subject string has the chance of values like 1234:5678, which would result in false positives with the above regex, then you could wrap the pattern in \b or some other assertion to make sure the time formatted numbers lie on their own.
It's probably easiest to match something like (\d{2}):(\d{2}) (preg syntax), then convert both submatches to an integer and check whether they are in the correct range.
preg_match_all('/([0-2][\d]):(\d{2})/', $string, $matches)
Now $matches[0] array contains all human readable times.
If you wish to print those along with specific date, feed each time through strtotime() function, like this
foreach ($matches[0] as $time) echo date('Y-m-d H:i:s', strtotime($time));