Today, I have thousands of files that I want to modify at a time or change the suffix, but I have to manually modify them one by one. I have to change the suffix several days before I come up with a solution, you can use php to write a program that modifies the extension of a file name. Let's take a look at the method below. Today, I have thousands of files that I want to modify at a time or change the suffix, but I have to manually modify them one by one. I have to change the suffix several days before I come up with a solution, use php to write a program that modifies the filename/filename extension. The following describes how to modify the filename/filename extension.
Script ec (2); script
Several key functions.
Is_dir ($ dirname) // determines whether a file name is a directory.
Opendir ($ dirname) // open a folder
Readdir ($ dir_stream) // The function returns the entries in the directory handle opened by opendir ().
Pathinfo ($ path) // The function returns the file path information in the form of an array.
For example, p10000036 in the current folder
For example, the following is an array of p10000036.jpg file paths under the folder:
Array
(
[Dirname] =>.
[Basename] => p1011236.jpg
[Extension] => jpg
[Filename] => p1038536
)
Rename (oldname, newname, context) // rename a file or directory. If the call succeeds, the function returns true. If it fails, false is returned.
The Code is as follows: |
|
Function fileRename ($ dir, $ srcExtension, $ desExtension ){ If (! Is_dir ($ dir )){ Echo "{$ dir} is not a valid directory! N "; Exit (); } $ Handler = opendir ($ dir ); // List all objects in the $ dir directory While ($ fileName = readdir ($ handler ))! = False ){ If ($ fileName! = '.' & $ FileName! = '..'){ // '.' And '..' Point to the current directory and the parent directory respectively. $ CurDir = $ dir. '/'. $ fileName; If (is_dir ($ curDir )){ // If the directory is used, recursive operation is performed. FileRename ($ curDir, $ srcExtension, $ desExtension ); } Else { // Obtain the file path information $ Path = pathinfo ($ curDir ); // Print_r ($ path ); If ($ path ['extension'] ==$ srcExtension ){ $ Newname = $ path ['dirname']. '/' . $ Path ['filename']. ".". $ desExtension; Rename ($ curDir, $ newname ); Echo $ curDir. '-->'. $ newname. "n "; } } } } } FileRename (".", "JPG", "jpg "); ?> |
The usage method is very simple. We can keep the image in the same directory as the php file and then run php.