Hi Dear All
I have 1000s of JPGs Images.
Names like S-KHI-1233
Now I need To rename all the images and new name should be last 4 numeric digits like 1233.
For all 1000 JPGs I want to do this.
if image name is S-KHI-1964 then new name should be 1964
and if name S-LAK-1854 then new name should be 1854.

Dani AI

Generated

A short, safe plan to rename files like S-KHI-1233.jpg to 1233.jpg for large batches.

Run a small command-line script (PHP CLI or Python) instead of through a browser, back up the folder first, and do a dry run that prints the old -> new mapping. As noted, applying a regex to the full path breaks results — extract the base filename before matching. Also normalize the extension (case-insensitive .jpg/.JPG), handle spaces in names, and avoid running long operations under the web server (permissions, timeouts).

Recommended workflow: (1) produce a dry-run list of candidate renames and inspect it; (2) match exactly the final four digits before the extension and skip files that do not match; (3) build the target name with extension and check for collisions — if two files would become the same name, append an incremental suffix (e.g., _1); (4) write the mapping to a CSV for easy rollback; (5) after verifying the dry run, toggle the script to perform renames. For GUI alternatives see and , but scripting gives repeatable control for thousands of files.

Example Python implementation (dry run by default — change dry_run to False to perform renames):

#!/usr/bin/env python3
import os, re, sys, csv

dry_run = True
d = sys.argv[1] if len(sys.argv) > 1 else '/path/to/simimage'
mapping = []

for fname in os.listdir(d):
    path = os.path.join(d, fname)
    if not os.path.isfile(path):
        continue
    m = re.search(r'(\d{4})(?=\.[jJ][pP][gG]$)', fname)
    if not m:
        continue
    digits = m.group(1)
    ext = os.path.splitext(fname)[1].lower()
    dest = os.path.join(d, digits + ext)
    i = 1
    while os.path.exists(dest):
        dest = os.path.join(d, f"{digits}_{i}{ext}")
        i += 1
    print(f"{path} -> {dest}")
    mapping.append((path, dest))
    if not dry_run:
        os.rename(path, dest)

with open('rename_map.csv','w',newline='') as f:
    csv.writer(f).writerows(mapping)

Notes: run from a shell account with appropriate permissions, test on a small subset, and keep the CSV mapping to undo or audit changes.

Recommended Answers

All 11 Replies

I've used this: http://www.1-4a.com/rename/

But you can just search google for file renamer if you want another one.

Use regular expression:

eg:

$name = 'S-KHI-1233';

$name = preg_replace("/[^0-9]/", '', $name);

But I have these JPGs in the folder name IMAGES.
How I can apply this code?

Hi Dear All
I have 1000s of JPGs Images.
Names like S-KHI-1233
Now I need To rename all the images and new name should be last 4 numeric digits like 1233.
For all 1000 JPGs I want to do this.
if image name is S-KHI-1964 then new name should be 1964
and if name S-LAK-1854 then new name should be 1854.

i am not sure. i think this is help ful to you. checkit once.

But I have these JPGs in the folder name IMAGES.
How I can apply this code?

PHP has numerous ways to traverse directories. Probably the simplest is the glob() function. (PHP4.3+)

http://php.net/manual/en/function.glob.php

You can use it like this:

// get an array of all .jpg files
$files = glob("*.jpg");
foreach ($files as $filename) {
    // make sure we have a file
    if (is_file($filename)) {
        // remove non-digits
        $newname = preg_replace("/[^0-9]/", '', $filename);
        // rename file
        rename($filename, $newname);
    }
}

I have change this according to my path but its not doing any thing as my images are stored in simimage Folder in server.

<?

// get an array of all .jpg files
$files = glob($_SERVER['DOCUMENT_ROOT']."/simimage/.jpg");
foreach ($files as $filename) {
    // make sure we have a file
    if (is_file($filename)) {
        // remove non-digits
        $newname = preg_replace("/[^0-9]/", '', $filename);
        // rename file
        rename($filename, $newname);
    }
}

?>

I have change this according to my path but its not doing any thing as my images are stored in simimage Folder in server.

<?

// get an array of all .jpg files
$files = glob($_SERVER['DOCUMENT_ROOT']."/simimage/.jpg");
foreach ($files as $filename) {
    // make sure we have a file
    if (is_file($filename)) {
        // remove non-digits
        $newname = preg_replace("/[^0-9]/", '', $filename);
        // rename file
        rename($filename, $newname);
    }
}

?>

Try:

$files = glob($_SERVER['DOCUMENT_ROOT']."/simimage/*.jpg");

Also, I just noticed that glob returns false on error. So you may want to catch that:

$files = glob($_SERVER['DOCUMENT_ROOT']."/simimage/.jpg");
if ($files) {
   /* rename your files */

} else {
  /* do your error handling */
}

Code is not showing anything in filename variabe when i use *
but when i put name ALU N-RMB-8221 manually it shows path like
C:/xampp/htdocs/simimage/ALU N-RMB-8221.jpg

$dir=$_SERVER['DOCUMENT_ROOT'];
$files = glob($dir."/simimage/ALU N-RMB-8221.jpg");

foreach ($files as $filename) 
	{
	echo $filename;
	}

no-1111.jpg stored in simimage and its showing error .
Its also gives error when I use * inplace of no-1111

<?

// get an array of all .jpg files
$dir=$_SERVER['DOCUMENT_ROOT'];
$files = glob($dir."/simimage/no-1111.jpg");



// make sure we have a file   
   if (is_file($files))
   { 

	foreach ($files as $filename) 
	{
 
	    // remove non-digits
        $newname = preg_replace("/[^0-9]/", '', $filename);
		
        // rename file
        rename($filename, $newname.".jpg");
    }
	}

	else 
	{
	echo "error";
	}


?>

no-1111.jpg stored in simimage and its showing error .
Its also gives error when I use * inplace of no-1111

<?

// get an array of all .jpg files
$dir=$_SERVER['DOCUMENT_ROOT'];
$files = glob($dir."/simimage/no-1111.jpg");



// make sure we have a file   
   if (is_file($files))
   { 

	foreach ($files as $filename) 
	{
 
	    // remove non-digits
        $newname = preg_replace("/[^0-9]/", '', $filename);
		
        // rename file
        rename($filename, $newname.".jpg");
    }
	}

	else 
	{
	echo "error";
	}


?>

First make sure you're getting all the files:

// get an array of all .jpg files
$dir=$_SERVER['DOCUMENT_ROOT'];
$files = glob($dir."/simimage/*.jpg");

var_dump($files);

When you do var_dump() it should show you all the values in the $files array. See that you have all the jpeg files.

The thing is that your regular expression is not correct, since now you're using absolute paths.

So change it to:

$newname = preg_replace("/([\/\\\]+)([^0-9\/\\\]+)([0-9]+)\.jpg$/i", '\\1\\3.jpg', $filename);

The regular expression matches any non-digits following a / or \ (directory separator).
It then matches any digits following that, ending with .jpg. It replaces the string with only the digits and .jpg, hence removing the non-digits after the directory separator.

OK I will try.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.