Home > front end >  How to write a regular expression for 5 scenarios of Date/Time?
How to write a regular expression for 5 scenarios of Date/Time?

Time:06-24

I am looking for a solution to regular expression that would take/accept 5 variations of Date/Time

  • 01/01/2022
  • 12:12:00
  • Time: 12:12:00
  • Date: 01/01/2022
  • Date/Time: 01/01/2022 12:12:00

So far all I have working is the following: But the Date: ... and 01/01/2022 are no triggering. So far this is the best I could come up with the resources on the internet.

preg_match('/(^)?((date|time|(date(?:(?!\/time))?\/time))\:.)?(\d{1,2}\/\d{1,2}\/\d{4})?(.)?(\d{1,2}\:\d{1,2}\:\d{1,2})/')

This is not for date validation. This information has already been updated, and is only being selected. I needed to separate the values so incase one was stored 1 way on the record, and differently on another record. The purpose is to parse a record and turning it into an object. This question has been answered.

https://onlinephp.io demo

CodePudding user response:

Based on the information previously gathered, the best route is to simply use:

preg_match('/(^)?((date|time|(date(?:(?!\/time))?\/time))\:)?(.*)/im');

That way in the 5th field will be the timestamp (date?/time), and in the group 3 it will tell its name (Date/Time/Date-Time).

CodePudding user response:

  • This is not for date validation.
  • regular expression that would take/accept 5 variations of Date/Time

Ok, so to capture and extract date and time strings, you can make your regex much simpler by:

  • Stripping of Date:, Time:, Date/Time: using str_ireplace. Now, we are only left with actual date and time values to match.

  • Creating a regex to match a date format of dd/mm/YYYY as \d\d/\d\d/\d{4} and similarly for time as HH:ii:ss as \d\d:\d\d:\d\d. Now, we perform optional matches for both groups using ?.

Snippet:

<?php

$tests = [
        '01/01/2022',
        '12:12:00',
        'Time: 12:12:00',
        'Date: 01/01/2022',
        'Date/Time: 01/01/2022 12:12:00'
    ];
    
foreach($tests as $test){
    preg_match('/(Date\/Time|Time|Date)\:/', $test, $possible_metadata);
    $metadata = $possible_metadata[1] ?? "";
    var_dump($metadata);
    $test = trim(str_ireplace(['Date/Time:','Time:','Date:'],'', $test));
    preg_match('/^(\d\d\/\d\d\/\d{4})?\s*(\d\d:\d\d:\d\d)?$/', $test, $matches);
    print_r($matches);
}

Online Demo

  • Related