Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/298.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用php preg_match和regex从字符串中分解日期_Php_Regex_Date_Preg Match - Fatal编程技术网

如何使用php preg_match和regex从字符串中分解日期

如何使用php preg_match和regex从字符串中分解日期,php,regex,date,preg-match,Php,Regex,Date,Preg Match,我正在处理包含日期的字符串。日期在该字符串中的显示方式有多种: “…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中的完整字符串中分离/分解它。有什么想法吗 我想我需要用regex创建一个模式,然后用preg_match匹配它。这是路吗?不幸的是,我不

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

“…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中的完整字符串中分离/分解它。有什么想法吗

我想我需要用regex创建一个模式,然后用preg_match匹配它。这是路吗?不幸的是,我不太喜欢正则表达式。有人能帮我从随机字符串中获取我的单个日期块吗?

试试:

$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字符:

// 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];
}
function find_date($string) {
    preg_match("/\d{2}\.\d{2}\.\d{4} \d{2}:\d{2}/",$string,$matches);
    return $matches[0];
}