开发者

How to explode date from a string using php preg_match and regex

开发者 https://www.devze.com 2022-12-10 00:37 出处:网络
I am processing strings with a date somewhere in it. There are different ways the date canappear in this string:

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.开发者_StackOverflow社区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?


$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];


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]);


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);


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"


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];
}
0

精彩评论

暂无评论...
验证码 换一张
取 消