简体   繁体   中英

Renaming Alphanumeric images with PHP

I have almost 10,000 images in a Folder with image name like

Abies_koreana_Blauer_Pfiff_05-06-10_1.jpg
Abies_koreana_Prostrate_Beauty_05-05-10_2.jpg
Chamaecyparis_obtusa_Limerick 06-10-10_3.jpg
Fagus_sylvatica_Dawyck_Gold_05-02-10_1.jpg

What i want do is rename the images using PHP so that only the characters remain in the image name want to delete the Numeric part so for example the above images would look like

Abies_koreana_Blauer_Pfiff.jpg
Abies_koreana_Prostrate_Beauty.jpg
Chamaecyparis_obtusa_Limerick.jpg
Fagus_sylvatica_Dawyck_Gold.jpg

Is this possible ? Or i have to do it manually ?

foreach file name do this

$new_filename = preg_replace("/(\w\d{0,2}[\W]{1}.+\.)/",".",$current_file_name);

so final function may look like this

function renameFiles($directory) 
{

$handler = opendir($directory);
while ($file = readdir($handler)) {
if ($file != "." && $file != "..") {

  if(preg_match("/(\w\d{0,2}[\W]{1}.+\.)/",$file)) {
    echo $file."<br/>";  
  }
rename($directory."/".$file,$directory."/".preg_replace("/(\w\d{0,2}[\W]{1}.+\.)/",".",$file));
}
}
closedir($handler);
}

renameFiles("c:/wserver");

Updated

You can do this with PHP (or bash). Your friends are RecursiveDirectoryIterator to walk through directories, preg_replace() to modify the file names, rename() to reflect changed filename on disk.

What you're trying to do can be done in ~10 lines of code. Using the ingredients above, you should be able to write a little script to change filenames yourself.

Update

throwing out the numeric parts (according to the examples given) can be done with a rather simple regular expression. Note that this will remove any numbers (-_ ) between the [az] filename and the suffix (".jpq"). So you won't get "foo3.png" but "foo.png". If this is a problem, the regex can be adjusted to meet that criteria…

<?php

$files = array(
    'Abies_koreana_Blauer_Pfiff_05-06-10_1.jpg',
    'Abies_koreana_Prostrate_Beauty_05-05-10_2.jpg',
    'Chamaecyparis_obtusa_Limerick 06-10-10_3.jpg',
    'Fagus_sylvatica_Dawyck_Gold_05-02-10_1.jpg',
);

foreach ($files as $source) {
    // strip all numeric (date, counts, whatever) 
    // characters before the file's suffix
    // (?= …) is a non-capturing look-ahead assertion
    // see http://php.net/manual/en/regexp.reference.assertions.php for more info
    $destination = preg_replace('#[ _0-9-]+(?=\.[a-z]+$)#i', '', $source);
    echo "'$source' to '$destination'\n";
}

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