我仍然不清楚 OP 的确切期望输出,但我对其他答案中的模式更加不知所措。我将发布这组解决方案以改进 Stackoverflow,因为我找不到合适的副本来关闭。
我使用波浪符~ 作为模式分隔符,这样模式中的/ 字符就不需要转义。另外,请注意我没有调用 \K 来重新开始全字符串匹配,因为没有理由这样做。
代码:(Demo)
$string='000001 0001 000000000000001975 00 02 0 000 2017/12/13 14:13:27';
var_export(preg_match('~\d{4}/\d{2}/\d{2}~',$string,$out)?$out:[]); // date
echo "\n\n";
var_export(preg_match('~\d{2}:\d{2}:\d{2}~',$string,$out)?$out:[]); // time
echo "\n\n";
var_export(preg_match('~\d{4}/\d{2}/\d{2} \d{2}:\d{2}:\d{2}~',$string,$out)?$out:[]); // full datetime
echo "\n\n";
var_export(preg_match('~(\d{4}/\d{2}/\d{2}) (\d{2}:\d{2}:\d{2})~',$string,$out)?$out:[]); // capture date and time
echo "\n\n";
var_export(preg_match_all('~\d{4}/\d{2}/\d{2}|\d{2}:\d{2}:\d{2}~',$string,$out)?$out:[]); // capture date or time
echo "\n\n";
var_export(preg_match('~(\d{4})/(\d{2})/(\d{2}) (\d{2}):(\d{2}):(\d{2})~',$string,$out)?$out:[]); // capture date digits and time digits
输出:
// date
array (
0 => '2017/12/13',
)
// time
array (
0 => '14:13:27',
)
full date time
array (
0 => '2017/12/13 14:13:27',
)
// capture date and time
array (
0 => '2017/12/13 14:13:27',
1 => '2017/12/13',
2 => '14:13:27',
)
// capture date or time
array (
0 =>
array (
0 => '2017/12/13',
1 => '14:13:27',
),
)
// capture date digits and time digits
array (
0 => '2017/12/13 14:13:27',
1 => '2017',
2 => '12',
3 => '13',
4 => '14',
5 => '13',
6 => '27',
)
附言对于未来的读者,如果您需要比这更强大的日期验证,那么正则表达式可能不适合您的任务。