簡體   English   中英

PHP:從目錄和所有子目錄中的文件名中遞歸刪除括號

[英]PHP: recursively remove brackets from filenames in directory and all sub directories

我在刪除系統中上傳文件中的括號時遇到問題。

我能夠刪除單個目錄的文件中的括號,但我正在努力使其在同一文件夾的子目錄中遞歸工作。

我正在使用 str_replace 來查找括號 [ ] 並將它們替換為空白字符。

    $dir = $_SERVER["DOCUMENT_ROOT"]."/uploads" ; // what directory to parse

  if ( $handle = opendir ( $dir)) {
   print "Directory Handle = $handles\n" ;
   print "Files : \n" ;
    while ( false !== ($file = readdir($handle))) {
     if ( $file != "." && $file != ".." ) {
      $isdir = is_dir ( $file ) ;
       if ( $isdir == "1" ) {} // if its a directory do nothing
        else {
        $file_array[] = "$file" ; // get all the file names and put them in an array
        print "$file\n" ;
        } // closes else
      } // closes directory check
     } // closes while
  } // closes opendir
 //Lets go through the array
 $arr_count = count( $file_array ) ; // find out how many files we have found so we can initiliase the counter
 for ( $counter=1; $counter<$arr_count; $counter++ ) {
  print "Array = $file_array[$counter]\n" ; // tell me how many files there are
  $illegals = array("[","]");
  $new = str_replace ( $illegals, "", $file_array[$counter] ) ; // now create the new file name
  $ren = rename ( "$dir/$file_array[$counter]" , "$dir/$new" ) ; // now do the actual file rename
  print "$new\n" ; // print out the new file name
  }
 closedir ( $handle ) ;
echo $dir;

好的,所以我從遞歸重命名腳本中獲取了代碼並創建了我自己的清理腳本。 如果我搞砸了什么,請告訴我。 感謝您為我指明正確的方向 NIC3500

$path = $_SERVER["DOCUMENT_ROOT"]."/uploads" ;
$illegals = array("[","]");


$di = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS),
    RecursiveIteratorIterator::LEAVES_ONLY
);

foreach($di as $name => $fio) {

    //$newname = $fio->getPath() . DIRECTORY_SEPARATOR . strtolower( $fio->getFilename() );
    $newname = $fio->getPath() . DIRECTORY_SEPARATOR . str_replace ( $illegals, "", $fio->getFilename() );
    //echo $newname, "\r\n";
    rename($name, $newname);

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM