我正在处理其中包含日期的字符串。日期在此字符串中的显示方式有多种:

" ... 01.11.2009 18:00-21:00 ......“要么 “... 01.11.2009 18:00-02.11.2009 15:00 ......”要么 “... 01.11.2009 18:00 ......”

无论日期如何出现,我只需要开始日期“01.11.2009 18:00”。所以,如果有两场比赛,那就是第一场比赛。如何从php中的完整字符串中隔离/爆炸。任何想法?

我想我需要用正则表达式创建一个模式,然后将它与preg_match匹配。这是这样的吗?不幸的是,我没有进入正则表达式。任何人都可以帮助从随机字符串中获取我的单个日期块吗?

有帮助吗?

解决方案

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

其他提示

尝试:

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

如果您的日期格式如下,则每个日期的字符数始终相同。然后,您可以使用简单的substr()来获取开头的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);

试试这个:

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"

您可以使用以下函数提取该格式的第一个日期:

function find_date($string) {
    preg_match("/\d{2}\.\d{2}\.\d{4} \d{2}:\d{2}/",$string,$matches);
    return $matches[0];
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top