繁体   English   中英

使用正则表达式检查文件格式(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);

?>

我想知道是否可以使用正则表达式检查日志文件格式Ymd.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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM