Jason Bond
Jason Bond

Reputation: 47

get date in string php

I am trying to get the date out of sentences in php.. so for example

I am trying to get 10/8/2006 out of

"This building was cleaned on the 8th of October 2006 after a huge storm."

There is a github function for it https://github.com/etiennetremel/PHP-Find-Date-in-String but it fails in dates such as 1/5/2012.

I realize that given the varied nature of date strings, finding a date string in strings is so much tougher than just simple REGEX for a specific format, or simply strototiming a given string input..

does anyone have any good ideas?

Upvotes: 2

Views: 426

Answers (3)

BenLanc
BenLanc

Reputation: 2434

Firstly, I would start by looking for a few basic patterns and extracting them with a few passes of regular expression (mm/dd/yy and mm/dd/yyyy with \d{2]/\d{2}/\d{2,4}, then look for others, like \d{1,2}(th|st|rd)? Jan(uary)?|Feb(ruary)?|Mar(ch)?|Apr(il)?|May|Jun(e)?|Jul(y)?|Aug(ust)?|Sep(tember)?|Oct(ober)|Nov(ember)?|Dec(ember) etc)

It will almost certainly be quicker to write a few regular expressions and do it in passes than write one massive one.

Then, pass the stuff you extracted in to strtotime to get yourself a usable unix timestamp and do with what you need from that.

Caveats:

  • I haven't tried the regexes, there are obvious optimisations
  • Works on the assumption that your dates will always be USA style (mm/dd/yy, and not dd/mm/yy)

Upvotes: 1

BenB
BenB

Reputation: 2907

i think it will be more simple with regex. the problem is that aher ary many options of how the date is writen.

Upvotes: 0

Alex
Alex

Reputation: 2146

I don't think there is a working solution because 10/8/2010 is not telling too much... it can be 10 day or month... I think you can proceed with your regex :)

Upvotes: 1

Related Questions