我想在本月底归档当月的所有日志文件。为此,我使用以下代码:
<?php
error_reporting(E_ALL);
set_time_limit(0);
ob_implicit_flush();
date_default_timezone_set('Europe/Berlin');
function archive_file($overwrite)
{
//$log_file_name = date('Y-m-d',strtotime('-1 days')).'.log';
$log_file_name = date('Y_m_d').'.log';
$zip_file = date('Y_m').'_Update_log.zip';
if(file_exists($zip_file) && !$overwrite)
return false;
$zip = new ZipArchive();
if($zip->open('E:\\'.$zip_file,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true)
return false;
$package_dir = 'E:\log';
$files = scandir($package_dir);
foreach ($files as $file_name)
{
echo "\n *******\n";
echo $file_name;
echo "****************\n";
//log file format = Y-m-d.log
//if(file format = format) {
$zip->addFile('E:\\'.$log_file_name, $log_file_name);
//}
}
$zip->close();
}
echo "*****************************Archive files***************\n";
archive_file(false);
?>
我想知道我是否可以使用正则表达式来检查日志文件格式Y-m-d.log(2015-01-07.log),以便仅存档一个月的所有日志文件(例如1月)。
任何帮助将不胜感激
答案 0 :(得分:1)
试试这个:
$regex = '/[0-9]{4}\-(.*?)\-/';
$matches = null;
preg_match($regex, $file_name, $matches);
if(isset($matches[1]) && $matches[1] == '01') {
echo $file_name.' file is a log of january';
}
或者如果你不需要获得比赛:
if(preg_match('/[0-9]{4}\-01\-/', $file_name)) {
echo $file_name.' file is a log of january';
}
答案 1 :(得分:1)
试试这个符合你的逻辑:
preg_match('/'.date('Y_m').'_\d.*/', $file_name)