Preg match php дата

Validate that input is in this time format — «HH:MM» [closed]

sorry, but really? reading this without a comment is bah. why not use something as simple as this: $dateObj = DateTime::createFromFormat(‘d.m.Y H:i’, «10.10.2010 » .$timeStr); if ($dateObj !== false) < // valid time>else < //invalid time>but yeah, give +14 upvotes for reinventing the wheel

@Toskan: I think that’s a fine way to do it. I tried to follow the OP’s request to use preg_match , even though I don’t know the reasoning behind it. I know that I’ve asked questions before and had people tell me that I shouldn’t do what I was asking to do (rather than tell me how to do it) and it bothered me — of course I had a reason for asking for what I wanted. I don’t know what this poster’s reasoning is: maybe they’re using GeSHi to format dates in their language and so DateTime::createFromFormat isn’t available. Or maybe they’re just learning regex. I don’t know.

Simple function that validates a date (and/or time) without throwing exceptions. It takes the expected date format as a parameter:

function isValidDate(string $date, string $format = 'Y-m-d'): bool < $dateObj = DateTime::createFromFormat($format, $date); return $dateObj && $dateObj->format($format) == $date; > 

How it works: it converts the input date into a PHP DateTime object according to the passed $format , then compares this object with the original input date. If they match, the date is valid and has the expected format.

/* Valid Examples: */ isValidDate("2017-05-31"); isValidDate("23:15:00", 'H:i:s'); isValidDate("2017-05-31 11:15:00", 'Y-m-d h:i:s'); /* Invalid: */ isValidDate("2012-00-21"); isValidDate("25:15:00", 'H:i:s'); isValidDate("Any string that's not a valid date/time"); 

This is the best one. I don’t see why other people are using regex when there is an official DateTime Class. You know why? Some other people spent their time, and when a class is the official one provided for a language, usually it has been tested so many times, plus, it will for sure be generic, and considering international issues. Expecially when you’re dealing with date and times. Those people worked hours, consuming human and electrical energy. Don’t waste both, it’s the basis for a good developer 😉 I know, it’s an heavy tought, but it’s right

Читайте также:  Python увеличение числа на единицу

This can be used as a simple true/false check. The return value is false or an instance of the dateTime object, so a simple if(DateTime::createFromFormat(‘H:i’,$time)) is good for a lot of cases.

@Snapey the main problem with that approach is that createFromFormat accepts «stupid» values like month 13, or day 0. The date 2000-13-00 will be considered valid as it parses it as 2000-12-31.

Let’s imagine the time you want to check is $timeStr and has to be the format H:i according to the date specs. Using a regex for this is IMHO silly. This is so much easier to read:

$timeStr = " 02:00"; //example of valid time, note whitespace test($timeStr); $timeStr = "23:59"; //valid test($timeStr); $timeStr = "24:00"; //invalid test($timeStr); $timeStr = "25:00"; //invalid test($timeStr); $timeStr = "16:61"; // invalid test($timeStr); //tests 23:59 hour format function test($timeStr)< $dateObj = DateTime::createFromFormat('d.m.Y H:i', "10.10.2010 " . $timeStr); if ($dateObj !== false && $dateObj && $dateObj->format('G') == intval($timeStr))< //return true; echo 'valid 
'; > else< //return false; echo 'invalid
'; > >

Create an offSet date and validate against it to remove inputs like 25:00. $dateObjOffset = DateTime::createFromFormat(‘d.m.Y H:i’, «10.10.2010 » . ’24:00′); if($dateObjOffset

@LakshithaUdara good solution if for the case you want to have 24:00 as valid time, i added a solution for valid until 23:59 that is a bit simpler

Function that validates hours, minutes and seconds, according to the desired format:

function validTime($time, $format='H:i:s') < $d = DateTime::createFromFormat("Y-m-d $format", "2017-12-01 $time"); return $d && $d->format($format) == $time; > 

How to use:

$valid = validTime("23","H"); $valid = validTime("23:59","H:i"); $valid = validTime("23:59:59","H:i:s"); $valid = validTime("23:59:59"); 

valid = true

$valid = validTime("25","H"); $valid = validTime("01:60","H:i"); $valid = validTime("01:20:61","H:i:s"); $valid = validTime("01:20:61"); 

valid = false

You don’t need to hardcode «Y-m-d» and «2017-12-01» there, it just makes it more complicated to understand and less flexible imo

T30 says the truth, I’ve just tested. Btw, I don’t see why other people are using regex when there is an official DateTime Class. You know why? Some other people spent their time, and when a class is the official one provided for a language, usually it has been tested so many times, plus, it will for sure be generic, and considering international issues. Expecially when you’re dealing with date and times. Those people worked hours, consuming human and electrical energy. Don’t waste both, it’s the basis for a good developer 😉 I know, it’s an heavy tought, but it’s right.

@Funder The basis of good software engineering is using code the software engineer knows works. Many coders are scared of regex’s complexity. It takes real commitment to understand regex. PHP is a great language, but I have run into several PHP bugs. That’s what bug reporting is for. «usually it has been tested so many times, plus, it will for sure be generic, and considering international issues.» This is the «the guy I don’t know is always smarter than I» fallacy. Just about every PHP manual page has error and issue discussions below the description, including the DateTime class.

Источник

Date regex PHP

Date regular expressions can be used to validate if a string has a valid date format and to extract a valid date from a string.

Simple date regex (DD/MM/YYYY)

Below is a simple regex to validate the string against a date format (D/M/YYYY or M/D/YYYY). This however does not guarantee that the date would be valid. You can also replace \\/ with a separator you need.

Enter a text in the input above to see the result

 

ISO 8061 date regex (e.g. 2021-11-04T22:32:47.142354-10:00)

The ISO 8061 is an international standard for exchanging and serializing date and time data. For validating the format of ISO 8061 date and time and for extracting it a following regular expression could be used:

Enter a text in the input above to see the result

 

Enter a text in the input above to see the result

Notes on date string regex validation

While there are some regular expressions that allow more complex date validations, it is usually better to validate dates using special date and time libraries. For example, in PHP DateTime::createFromFormat can be used for these purposes. In this case, the validation will look like this:

Create an internal tool with UI Bakery

Discover UI Bakery – an intuitive visual internal tools builder.

Источник

What is the regex pattern for datetime (2008-09-01 12:35:45 )?

@Espo: I just have to say that regex is incredible. I'd hate to have to write the code that did something useful with the matches, such as if you wanted to actually find out what date and time the user typed.

It seems like Tom's solution would be more tenable, as it is about a zillion times simpler and with the addition of some parentheses you can easily get at the values the user typed:

If you're using perl, then you can get the values out with something like this:

$year = $1; $month = $2; $day = $3; $hour = $4; $minute = $5; $second = $6; 

Other languages will have a similar capability. Note that you will need to make some minor mods to the regex if you want to accept values such as single-digit months.

Just a comment to say that this regex wont detect if the date, the month or the time has a value superior to the maximum one. For example 2012-65-65 99:99:99 will work. Apart from that the regex is great!

The regular expression shown is not intended to validate the date. It's intended to check the syntax of a string to see whether it looks like it could be a date. After getting the values out, you can validate the given date using normal date library functions.

This regex gives a match even for a date like 2020-99-99 99:99:99 which is not right as mentioned by @darkheir

A simple version that will work for the format mentioned, but not all the others as per @Espos:

This RE validates both dates and/or times patterns. Days in Feb. are also validated for Leap years. Dates: in dd/mm/yyyy or d/m/yy format between 1/1/1600 - 31/12/9999. Leading zeroes are optional. Date separators can be either matching dashes(-), slashes(/) or periods(.) Times: in the hh:MM:ss AM/PM 12 hour format (12:00 AM - 11:59:59 PM) or hh:MM:ss military time format (00:00:00 - 23:59:59). The 12 hour time format: 1) may have a leading zero for the hour. 2) Minutes and seconds are optional for the 12 hour format 3) AM or PM is required and case sensitive. Military time 1) must have a leading zero for all hours less than 10. 2) Minutes are manditory. 3) seconds are optional. Datetimes: combination of the above formats. A date first then a time separated by a space. ex) dd/mm/yyyy hh:MM:ss

Edit: Make sure you copy the RegEx from the regexlib.com website as StackOverflow sometimes removes/destroys special chars.

This answer provides a good regular expression, but not an answer for the actuall question. The question is to validate dates separated by "-" and not "/" as this answer describes.

Источник

i want php pattern for date as DD/MM/YYYY [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.

I want a regular expression to use in preg_match to check whether or not a date is in the pattern DD/MM/YYYY . I tried the code below, but it didn't work:

preg_match("#^29*111*11962?#", $date); 

This is really poor question, think about others taking their time to answer your question. Please be more patient before asking questions. There's no effort visible in this question.

And it's not exactly hard to google either. Possible duplicate of What is the MM/DD/YYYY regular expression and how do I use it in php?

but now i have Charles Hooper's answer it is : date_parse_from_format('d/M/Y', $date); >>> it is good answer it's helped me

3 Answers 3

  • From the start of the string,
  • Look for any number of characters in the range 1 through 3, or the character 1
  • Look for a literal 1
  • Look for any number of characters in the range 1 through 1, or the character 2
  • Look for a literal 1
  • Look for either one or zero of the characters 1, 9, 5, 0 through 2, 0, 1 or 3

It very obviously doesn't make sense.

You can't validate a date in regex, since dates are not regular. You have different numbers of days in each month, leap years, and a bunch of other stuff. You would be better off separating your date into pieces (use explode ) and check it with checkdate()

Источник

Preg_match for a date

I am trying to match a date in PHP using preg_match, split it and assign parts of it to an array, the date looks like "20100930", here is the code I am using:

// Make the tor_from date look nicer $nice_from = $_POST['tor_from']; $matches = array(); $ideal_from = ''; preg_match('/\d\\d\\d\/', $nice_from, $matches, PREG_OFFSET_CAPTURE, 0); // if (isset($matches[0])) $nice_from = $matches[0]; echo $matches[0]; echo "
"; echo $matches[1]; echo "
"; echo $matches[2]; echo "
"; echo $matches[3]; echo "
";

Ive been using: http://php.net/manual/en/function.preg-match.php and PHP preg_match question to formulate ideas on how to do this, however I have had no luck in getting it to work. Any help would be greatly appreciated.

5 Answers 5

Although regex isn't really a good solution for parsing a date in YYYYMMDD format, let's walk through why your pattern isn't working.

Your pattern \d\\d\\d\ says: "match 4 digits ( \d ), followed by a backslash character ( \\ ), followed by the letter d twice ( d ), followed by another backslash ( \\ ) and then finally another two d's ( d )."

As you might have figure out by now, you don't want the double slashes!

Will match 4 digits, followed by 2 digits, and then another 2 digits.

Furthermore, you are not specifying any capturing groups, so your subpatterns will never be filled. What you probably meant was:

Источник

Оцените статью