0

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?

Community
  • 1
  • 1
Purus
  • 5,701
  • 9
  • 50
  • 89

3 Answers3

1
<?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";

    }
}
?>
Frederick Behrends
  • 3,075
  • 23
  • 47
0

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);
}
Satish Sharma
  • 9,547
  • 6
  • 29
  • 51
0

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);
}
Bilal
  • 2,645
  • 3
  • 28
  • 40