gary00ie Posted October 1, 2011 Share Posted October 1, 2011 Hi, I need a fast function to extract the year (YYYY) from a string. The string will be YYYY-MM-DD or DD-MM-YYYY. Would a regular expression help with this? Maybe something like: echo preg_match($dateStr); Any help would be appreciated. I'm getting nowhere with this. Thanks in advance Quote Link to comment https://forums.phpfreaks.com/topic/248238-php-date/ Share on other sites More sharing options...
smerny Posted October 1, 2011 Share Posted October 1, 2011 preg_match('/\d{4}/', $dateStr, $matches); will put every match of a 4 digit number in an array $matches Quote Link to comment https://forums.phpfreaks.com/topic/248238-php-date/#findComment-1274775 Share on other sites More sharing options...
AyKay47 Posted October 1, 2011 Share Posted October 1, 2011 if those are the only characters in the string.. you can use this simple pattern for your preg_match.. $pattern = "~\d{4}~"; Edit: above poster beat me to it... Quote Link to comment https://forums.phpfreaks.com/topic/248238-php-date/#findComment-1274776 Share on other sites More sharing options...
gary00ie Posted October 1, 2011 Author Share Posted October 1, 2011 Thank you both for the replies. So could I have - as the delimiter also? $dateStr = '2010/11/11'; // or 2010-11-11 echo preg_match('/\d{4}/', $dateStr, $matches); Also, $dateStr could also be: DD-MM-YYYY also, correct? Quote Link to comment https://forums.phpfreaks.com/topic/248238-php-date/#findComment-1274777 Share on other sites More sharing options...
cunoodle2 Posted October 1, 2011 Share Posted October 1, 2011 There may be a way to do this with a regular expression but I have no clue how to do that so I would do something like this.. <?php //this case would be MM-DD-YYYY if ((strpos($dateStr, "-") == 2) && (strrpos($dateStr, "-") == 5) //then strip off the last 4 characters //this case would be YYYY-MM-DD else if ((strpos($dateStr, "-") == 4) && (strrpos($dateStr, "-") == 7) //then strip off the first 4 characters ?> would this work? Quote Link to comment https://forums.phpfreaks.com/topic/248238-php-date/#findComment-1274778 Share on other sites More sharing options...
xyph Posted October 1, 2011 Share Posted October 1, 2011 Thank you both for the replies. So could I have - as the delimiter also? $dateStr = '2010/11/11'; // or 2010-11-11 echo preg_match('/\d{4}/', $dateStr, $matches); Also, $dateStr could also be: DD-MM-YYYY also, correct? All of those are correct. Quote Link to comment https://forums.phpfreaks.com/topic/248238-php-date/#findComment-1274784 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.