OK so basically I have a string which represents a date but the formatting is non-uniform (i.e. it could be '2000', '12th January 1999', '01-01-2000', etc. (The year will always be a 4 digit number though)) So I need to extract just the year from this string in PHP. Clearly a regex is needed but tbh I've only ever used them very briefly in the past so a nudge in the right direction would be appreciated
Use 'strtotime' to parse the number in whatever format, to turn it into an integer timestamp. Then you can use 'date' to extract the token you need. e.g. PHP: $fuzzyDate = "12th Jan 1999"$timestamp = strtotime($fuzzyDate);$year = date("Y", $timestamp); // Will be "1999"$month = date("m", $timestamp); // ..."01"$dayOfWeek = date("l", $timestamp); // ..."Tuesday" Have fun!
PHP: $str_date = "12th August 2007";$matches = array();if (preg_match('/(\d{4})/', $str_date, $matches)) { $year = $matches[1];}print_r((int)$year);
Wicked, last 2 work great, thanks dudes mutznuts, that would only work if the date was 'xx-xx-xxxx' which (as in my first post), that is not always going to be the case.