Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex to get date yyyy-mm-dd from any string

first of all excuse me for not being regex familiar that much.What I Would like is a regex that will extract a date like mysql date from any type of string. Until now I was using this : ^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$

However now I want to extract date patterns from other strings and datetime strings I tried altering the regex to ^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1]). based on some online regex testers, but it fails. Also some times it gave me a result with a 3 digit day.

In other words sting starts with, yyyy-mm-dd and is followed up by spaces characters numbers or anything. How do I extract the date?

UPDATE

I'm testing regex with preg_match here: http://www.pagecolumn.com/tool/pregtest.htm

so far the only thing that seems to work is

[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])
like image 962
0x_Anakin Avatar asked Oct 24 '13 10:10

0x_Anakin


1 Answers

Try this: you can use preg_match() or preg_match_all()

   $dateArray = preg_match("/(\d{4}-\d{2}-\d{2})/", $str, $match);

Then use strtotime and date

$date = date('Y-m-d',strtotime($match[0]));
like image 191
Sunil Kumar Avatar answered Oct 13 '22 00:10

Sunil Kumar