使用正则表达式检查文件格式 (php)

check file format with regular expression (php)

我想在本月底归档该月的所有日志文件。为此,我使用以下代码:

<?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) 以仅归档一个月的所有日志文件(例如 january )。

任何帮助将不胜感激

试试这个:

$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';
}

试试这个它会符合你的逻辑:

preg_match('/'.date('Y_m').'_\d.*/', $file_name)