Help writing a function to extract dates from a string

I’m guessing this function would require some kind of expression, but I really suck at expressions, and so am asking for a little help. I need a function that will search a given string for a date and return both the date in a specified format (YYYY-MM-DD) and the string with the date removed.

For example, here are some sample strings:

Dresden Dolls Space Gallery Portland Oregon 06-02-2005
Dead Weather House Of Blues Boston 18/07/2009
Dirty Fuzz Harmonie Bonn 23.03.2007

The dates are always in DD-MM-YYYY format, but sometimes the delimiter is a hyphen, period, or a slash.

After running each string through the function, I should have an array of two variables, one containing the date in YYYY-MM-DD format and the original string with the date removed. For example:

Dresden Dolls Space Gallery Portland Oregon ---- 2005-02-06
Dead Weather House Of Blues Boston ---- 2009-07-18
Dirty Fuzz Harmonie Bonn ---- 2007-03-23

So, are the dates always DD MM YYYY ?

Edit: NVM, I should posts properly! :stuck_out_tongue:


<?php
$strings = array(
    'Dresden Dolls Space Gallery Portland Oregon 06-02-2005',
    'Dead Weather House Of Blues Boston 18/07/2009',
    'Dirty Fuzz Harmonie Bonn 23.03.2007'
);

foreach($strings as $string){
    $timestamp = strtotime(
        vsprintf(
            '&#37;s-%s-%s',
            preg_split(
                '~[-./]~',
                end(
                    explode(
                        ' ',
                        $string
                    )
                )
            )
        )
    );
    echo date('r', $timestamp), '<br />';
}

/*
    Sun, 06 Feb 2005 00:00:00 +0000
    Sat, 18 Jul 2009 00:00:00 +0100
    Fri, 23 Mar 2007 00:00:00 +0000
*/
?>

It works, but there are an awful lot of assumptions there. You would, IMHO, be better looking at using a Regular Expression to obtain the string/date.


preg_match('/(\\d{1,2})[\\.\\-\\/](\\d{1,2})[\\.\\-\\/](\\d{4})/', $str, $matches);

That matches all dates with hypens, slashes and dots.
It also matches for example 1-1-2010 (as opposed to 01-01-2010) because of the {1,2}

Thanks guys, you’ve helped me out a lot. I’ve got the function working now. :slight_smile: