解析文件名,重命名文件,然后移动到另一个目录

Parse filename, rename file, then move to another directory

我有一个文件夹,其中包含这样命名的文件: MDalarm_20201129_061408.mkv

我应该像这样重命名它们: dd_mm_yy_hhss.mkv 然后根据日期将它们移动到目录中。例子: MDalarm_20201129_061408.mkv 将变为:

29_11_20_0614.mkv 并将移动到文件夹 29_11_20

$year = date("Y");
$month = date("m");
$day = date("d");
 
$directory = "$day_$month_$year";


if(!is_dir($directory))
{
    mkdir($directory, 755, true);
}

error_reporting(0);
$video=array();
$path= 'record';
$video=glob("$path/*.mkv");
$quanti=count($video);

foreach($video as $chiave => $nome)

{       
        $componenti=explode("_", $nome);
 }

这是执行此操作的脚本。我在我的 Windows 10 上试过了,它在这里运行良好

编辑:现在你只需要更改扩展变量,它会很好地处理它

<?php 

$extension = "mkv";
$allFiles = glob("*.".$extension);

foreach($allFiles as $filename){
    $getYearDayMonth = getYearDayMonth($filename);
    if (!file_exists($getYearDayMonth)) {
        mkdir($getYearDayMonth, 0777, true);
    }
    $hhss = "";
    preg_match("/.*_(\d\d\d\d\d\d)\./",$filename,$hhss);
    $hhss = $hhss[1];
    file_put_contents($getYearDayMonth."/".$getYearDayMonth."_".$hhss.".".$extension,file_get_contents($filename));
}

function getYearDayMonth($filename){
    $getYearDayMonth = "";
    $getYear = "";
    $getMonth = "";
    $getDay =  "";
    preg_match("/MDalarm_(.+?)_/",$filename,$getYearDayMonth);
    $getYearDayMonth = $getYearDayMonth[1];
    preg_match("/\d\d\d\d/",$getYearDayMonth,$getYear);
    $getYear = $getYear[0];
    preg_match("/\d\d\d\d(\d\d)/",$getYearDayMonth,$getMonth);
    $getMonth = $getMonth[1];
    preg_match("/\d\d\d\d\d\d(\d\d)/",$getYearDayMonth,$getDay);
    $getDay = $getDay[1];

    return $getYear."_".$getMonth."_".$getDay;
}


?>