Skip to content
Advertisement

What is the best way to rename all the images in a folder in php?

I’m new in PHP and would like to know how I can rename all the pictures in a folder in PHP.

I have a folder that contains different pictures all named :

- BBBOF1_0090_A.jpg
- BBBOF1_0090_B.jpg
- BBBOF1_0090_C.jpg
- BBDOTR_0070_A.jpg
- BBDOTR_0070_B.jpg
....

I would like to add a K in front of the name of each image and change the numbers 1,2,3,4,5… to a,b,c,d

In the end I should have :

- KBBBOF1_0090_1.jpg
- KBBBOF1_0090_2.jpg
- KBBBOF1_0090_3.jpg
- KBBDOTR_0070_1.jpg
- KBBDOTR_0070_2.jpg
....

How do I do it please? I tried with the rename function to add the K but for the part where the letters are replaced by numbers I don’t see how to do it.

<?php

$path = $_POST['path'];


   $dir    = $path;
   $allFiles = scandir($dir);

   foreach($allFiles as $file) {

        if (!in_array($file,array(".","..")))
      { 
  
      $file = $dir.$file;
      $filename = basename( $file );

   
        $newname = "K$filename";

        rename ("C:/wamp64/www/KMD/Photos/$filename", "C:/wamp64/www/KMD/new/$newname");
        
    }


  }

    
echo "good !";
?>

Advertisement

Answer

There may be an easier way to do this but here is one way:

$newname = "K$filename"; // Start from here
preg_match( '/_([A-Z]).jpg/', $newname, $matches ); // Get last letter
$char = ord($matches[1])-ord('A')+1; // Turn letter into corresponding number (A->1, B->2, etc.)
$newname = preg_replace( '/_([A-Z]).jpg/', "_".$char, $newname ); // Replace letter with number
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement