简体   繁体   中英

Move and rename folders php

I'm working with a script where i want to move folders to another directory,and give the folders new name. I think i need to explode a string? But i don't get it to work properly. Example i want the folder with original name: 351437-367628 and to have new name: from start to the hyphen.

I'm moving the folder by the glob and rename function.

<?php
    if ($handle = opendir('folders')) {
        while (false !== ($fileName = readdir($handle))) {
            $newName = str_replace("-#","",$fileName);
            rename($fileName, $newName);
        }
        closedir($handle);
    }
?>

You can use explode() function as

$fileName = '351437-367628';
$newNametemp = explode("-",$fileName);
if(is_array($newNametemp)){
    $newName = $newNametemp[0];
    print_r($newName); // will return 351437,i.e. new name from start to hyphen
    rename($fileName, $newName);
}

To get all directories

$dir = new DirectoryIterator('path');
foreach ($dir as $fileInfo) {
    if ($fileInfo->isDir() && !$fileInfo->isDot()) {
        $fileName = $fileInfo->getFilename();
        $newNametemp = explode("-",$fileName);
        if(is_array($newNametemp)){
            $newName = $newNametemp[0];
            print_r($newName); 
            rename($fileName, $newName);
        }
    }
}

if you are using a lower version of PHP try

if ($handle = opendir('path')) {
    while (false !== ($fileName = readdir($handle))) {
        if(is_dir($fileName) && ($fileName != '..' && $fileName != '.')){
            $newNametemp = explode("_",$fileName);
            if(is_array($newNametemp)){
                $newName = $newNametemp[0];
                print_r($newName); 
                echo "<br/>";
                rename($fileName, $newName);
            }
        }
    }
    closedir($handle);
}

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