jcadima
5/3/2015 - 2:30 AM

Remove blank spaces from files in a directory

Remove blank spaces from files in a directory

<?php
// reference:
// http://stackoverflow.com/questions/1225321/using-php-to-rename-files-with-spaces


// Current Directory
   $dir = './';
    $dhandle = opendir($dir);
    // array that holds the files to be renamed
    $rename_files = array();

    if ($dhandle) {
    while (false !== ($fname = readdir($dhandle))) {
    	// do not put files to be renamed in the array if the file is a dot/directory or a .php file
        if ( ($fname != '.') && ($fname != '..') && !is_dir("./$fname" )  && array_pop( explode(".", $fname ) ) !== "php" )
             $rename_files[] = $fname;
         	 echo "READING ALL FILES: $fname <br>";
       }
       closedir($dhandle);
   }

   echo '<hr>';

   // Show the files to be renamed
    foreach($rename_files as $file)
    {
    	echo "FILES TO BE RENAMED: $file  <br>";
    }

   

    echo '<hr>';

    // 
    foreach($rename_files as $file)
    {
    	// replace blank spaces with empty space
        $new_name = str_replace(' ','',$file);
        rename("./".$file, "./".$new_name);
        echo "FILES WITHOUT BLANK SPACES:  $new_name <br>";
    }