Last active
August 29, 2015 14:06
-
-
Save Langmans/2b0489c9c204345d9b49 to your computer and use it in GitHub Desktop.
Match mysql dates in a string.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$d = function ($name, $length = '1,2') { | |
return sprintf('(?<%s>\d{%s}>)', $name, $length); | |
}; | |
$matches2time = function ($matches, $format = DateTime::W3C) { | |
$year = $month = $day = $time = $hour = $minute = $second = null; | |
extract($matches); | |
$dt = new DateTime(); | |
$dt->setDate((int)$year, (int)$month, (int)$day); | |
if (isset($time)) { | |
if (isset($second)) { | |
$dt->setTime((int)$hour, (int)$minute, (int)$second); | |
} else { | |
$dt->setTime((int)$hour, (int)$minute); | |
} | |
} | |
return is_int($format) ? $dt->format($format) : $dt->getTimestamp(); | |
}; | |
$sep = '[-_\s]+'; | |
$sep2 = "($sep|:)"; | |
$sep3 = "($sep|T)"; | |
$datepat = vsprintf( | |
"@(^|$sep)%s$sep%s$sep%s$sep3(?<time>$sep2%s($sep2%s)?)?($sep|$)@i", | |
array( | |
$d('year', 4), | |
$d('month', '1,2'), | |
$d('day', '1,2'), | |
$d('hour', '1,2'), | |
$d('minute', '1,2'), | |
$d('second', '1,2') | |
) | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment