views:

881

answers:

5

I am processing strings with a date somewhere in it. There are different ways the date can appear in this string:

"… 01.11.2009 18:00-21:00 …" or "… 01.11.2009 18:00-02.11.2009 15:00 …" or "… 01.11.2009 18:00 …"

Regardless how the date appears I only need the beginning date "01.11.2009 18:00". So if there are two matches it's just the first one. How can I isolate/explode this from the full string in php. any idea?

I guess I need to create a pattern with regex and then matching it with preg_match. Is this the way? Unfortunately I am not into regex very much. Could anyone help with getting my single date block from a random string?

A: 

Try:

$s = "… 01.11.2009 18:00-21:00 …… 01.11.2009 18:00-02.11.2009 15:00 …… 01.11.2009 18:00 …";
preg_match_all('!(\d{2}\.\d{2}\.\d{4}) \d{2}:\d{2}(-\d{2}:\d{2}|-\d{2}\.\d{2}\.\d{4} \d{2}:\d{2})?!', $s, $matches);
print_r($matches[1]);
cletus
A: 

if your date is formatted in the following manner you will always have the same number of characters for each date. You could then use a simple substr() to take the beginning X chars:

// example date strings
$date = date('m.d.Y h:i:S');
$date2 = date('m.d.Y h:i:S', strtotime('+50 days'));
$date_str = $date . '-' . $date2;

// get the first 10 characters for the date
$match = substr($date_str, 0, 10);
cballou
A: 
$matches = array();
$desired_date = '';
preg_match('/\d{2}\.\d{2}\.\d{4} \d{2}:\d{2}/', $string_containing_dates, $matches);
if (isset($matches[0])) $desired_date = $matches[0];
Ben
works fine. thanks very much!
Bernd Plontsch
A: 

Try this one:

preg_match_all(
    '/([0-9]{2}\.[0-9]{2}\.[0-9]{4} [0-9]{2}:[0-9]{2})' // linebreak added
    . '(?:-(?:[0-9]{2}\.[0-9]{2}\.[0-9]{4} )?(?:[0-9]{2}:[0-9]{2})?)?/',
    '" 01.11.2009 18:00-21:00 " or " 01.12.2009 18:00-02.12.2009 15:00 " '
    . 'or " 01.01.2009 18:00 "',
    $matches
);

print_r($matches[1]);
// "01.11.2009", "01.12.2009", "01.01.2009"
nickf
A: 

You can extract the first date in that format using the function below:

function find_date($string) {
    preg_match("/\d{2}\.\d{2}\.\d{4} \d{2}:\d{2}/",$string,$matches);
    return $matches[0];
}
Travis