简体   繁体   中英

Bulk update in php using some conditions for filename

I have a folder and have multiple files over there. The file has the below pattern for example.

The file names should be renamed from

file1.mp4.png
file2.flv.png
file3.xxx.png (xxx - can be anything)

to as follows (the last extension remains).

file1.png
file2.png
file3.png

Files having non-png extension should be left untouched.

I am using the logic mentioned in Bulk Rename Files in a Folder - PHP

$handle = opendir("path to directory");

if ($handle) {
    while (false !== ($fileName = readdir($handle))) {
        $newName = (how to get new filename) // I am struck here
        rename($fileName, $newName);
    }
    closedir($handle);
}

How best I can do this to do a bulk update?

<?php
// Select all PNG Files
$matches = glob("*.[pP][nN][gG]");

// check if we found any results
if ( is_array ( $matches ) ) {

    // loop through all files
    foreach ( $matches as $filename) {

        // rename your files here
        $newfilename = current(explode(".", $filename)).".png";
        rename($filename, $newfilename);
        echo "$filename -> $newfilename";

    }
}
?>

try this

$handle = opendir("path to directory");

if ($handle) {
    while (false !== ($fileName = readdir($handle))) {
        $arr_names = explode(".", $fileName);  
        $size = sizeof($arr_names);
        $ext = $arr_names[$size-1];
        if($fileName=="." || $fileName==".."  || is_dir($fileName))
        {
           continue; // skip png  
        }

         if($ext=='png' || $ext=='PNG')
         {
             $newName = $arr_names[0].".".$ext;         

             rename($fileName, $newName);
         }
    }
    closedir($handle);
}

Shortest using regex

$handle = opendir("path to directory");

if ($handle) {
    while (false !== ($fileName = readdir($handle))) {
        $newName = preg_replace("/\.(.*?)\.png$/", '', $fileName); // removes .xxx.png
        rename($fileName, ($newName . '.png')); // renames file1.png
    }
    closedir($handle);
}

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