Search code examples
phpbatch-rename

Rename Directory using PHP Script


I have a directory containing folders like

baseurl/2-435435435_323423/
baseurl/5_435435435_32423/
baseurl/3_543543543_2342342/

Now i want to rename all the folders from their original name to new name i.e. truncate last part separated by '_'. new names would be


baseurl/2-435435435/
baseurl/5_435435435/
baseurl/3_543543543/

$path_from = 'E:/documents/';
if(file_exists($path_from)){
    $files = scandir($path_from);
    foreach($files as $key1 => $file) {
        $newName = ? // I need this
        rename($path_from.$file,$path_from.$newName);
    }
}

Or Let me know if there is anyway in windows to rename batch without any script.


Solution

  • As you mention for getting only $newName, Just use substr and strrpos.

    strrpos - Find the numeric position of the last occurrence of a string

    $str = 'baseurl/3_543543543_2342342/';
    
    $pos = strrpos($str, "_");
    if ($pos === false){
        //do nothing
    }else
        $str = substr($str, 0, $pos)."/";
    
    echo $newName = $str; //baseurl/3_543543543/