Home > Enterprise >  search for date values in string
search for date values in string

Time:10-17

this my situation at the moment: I save a dynamic string into a variable $content.

With this code I get all values of my $content which has the number format x.xx

preg_match_all('/\d \,\d /m', $content, $matches);

Now I would like to get additionally all values which are dates. For example:

14.10.2021
10/14/2021
10. October 2021

The year could be also like 21 instead of 2021. Here are many version possible.

Is there also a preg_match_all solution for that? Or is there an way to say:

Give me all values of the string, where php found a valid date?

Thank you a lot !!

CodePudding user response:

Using the DateTime class is generally a good idea to work with dates but I guess that you need to extract them as your string does not only contain dates. Using a RegEx results in long patterns because of months:

\d{2}(\.|\/)?(\d{2}\1|\s(January|February|March|April|May|June|July|August|September|October|November|December)\s)(\d{4}|\d{2})

But it matches the following:

  • \d{2} 2 digits
  • (\.|\/)? an optional dot or slash (group capture n°1)
  • (
    • \d{2}\1 2 digits followed by group capture n°1
    • | or
    • \s(January|February|March|April|May|June|July|August|September|October|November|December)\s a month with spaces around
  • )
  • (\d{4}|\d{2}) 2 or 4 digits
  • Related