简体   繁体   中英

Rename files using PHP

I want to be able to rename files using PHP.

The following script checks if the new name exists. If it does (and it includes a suffix) the suffix will be incremented.

if(file_exists($fileName)) {
        $fileNewName= preg_replace_callback('/(?<=_)\d+(?=\.)/',                   
         function ($m) { return ++$m[0]; },
         $fileName);
 }

However, if the file does not include a suffix, none is added to the file.

Example:

filename_1.txt  becomes  filename_2.txt
however
filename.txt is not renamed.

Can you help me add the suffix (_1) is no suffix existed. Example:

filename.txt becomes filename_1.txt

Perhaps something like this (not tested):

if(file_exists($fileName)) {
    $fileNewName = preg_replace_callback('/(?:(?<=_)\d+)?(?=\.[^.]*$)/',                   
        function ($m) { return empty($m[0]) ? '_1' : ++$m[0]; },
         $fileName, 1);
}

In short, you make the beginning optional (?:(?<=_)\\d+)? and you ensure that the dot is the last (?=\\.[^.]*$) . Using a ternary operator when $m[0] is empty, you return '_1' else the incremented value.

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