简体   繁体   中英

Parse filename, rename file, then move to another directory

I have a folder containing files named like this: MDalarm_20201129_061408.mkv

I should rename them all like this: dd_mm_yy_hhss.mkv and then move them to a directory based on their date. example: MDalarm_20201129_061408.mkv will become:

29_11_20_0614.mkv and will be moved to folder 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);
 }

Here is script to do that. I tried it on my Windows 10 and it is working well here

Edit: Now you just need to change the extension variable and it will process it fine

<?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;
}


?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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