Jump to content

[SOLVED] Rename files in folder by replacing whitespace with underscore.


JMair

Recommended Posts

I've been given about 500 files to put on our website. I need to rename each file just to replace the whitespaces with an underscore. Instead of doing it by hand, there's got to be an easier way to do it. What functions can I use to aproach this problem?

Hi JMair,

 

Have a look here:

 

http://www.phpro.org/examples/Recursively-Rename-All-Files-In-Directory-With-RecursiveDirectoryIterator.html

 

You will probably need to edit the:

 

function safe_names($filename)
        {
            $filename = collapseWhiteSpace($filename);
            $filename = str_replace(' ', '-', $filename);
            $filename = preg_replace('/[^a-z0-9-.]/i','',$filename);
            return  strtolower($filename);
        }

 

i.e. perhaps change;

 

$filename = str_replace(' ', '-', $filename);

 

to:

 

$filename = str_replace(' ', '_', $filename);

 

for example but it should do what you need. 

 

Also, you may want to delete/edit the $filename = preg_replace('/[^a-z0-9-.]/i','',$filename); as required for what you want to achieve.

 

Essentially, upload all the files and then run this script.

 

Hope this helps.

Yes! Thank you. Below is the whole script with edits made to rename all files in the same directory this is run from and ONLY to replace whitespaces with an underscore.

<?php

/*** the target directory, no trailling slash ***/
$directory = '.';

try
    {
        /*** check if we have a valid directory ***/
        if( !is_dir($directory) )
        {
            throw new Exception('Directory does not exist!'."\n");
        }

        /*** check if we have permission to rename the files ***/
        if( !is_writable( $directory ))
        {
            throw new Exception('You do not have renaming permissions!'."\n");
        }

    
        /**
        *
        * @collapse white space
        *
        * @param string $string
        *
        * @return string
        *
        */
        function collapseWhiteSpace($string)
        {
            return  preg_replace('/\s+/', ' ', $string);
        }

        /**
        * @convert file names to nice names
        *
        * @param string $filename
        *
        * @return string
        *
        */
        function safe_names($filename)
        {
            $filename = collapseWhiteSpace($filename);
            $filename = str_replace(' ', '_', $filename);
            //$filename = preg_replace('/[^a-z0-9-.]/i','',$filename);
            return  ($filename);
        }

        $it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory, 0));
        /*** loop directly over the object ***/
        while($it->valid())
            {
            /*** check if value is a directory ***/
            if(!$it->isDot())
            {
                if(!is_writable($directory.'/'.$it->getSubPathName()))
                {
                    echo 'Permission Denied: '.$directory.'/'.$it->getSubPathName()."\n";
                }
                else
                {
                    /*** the old file name ***/
                    $old_file = $directory.'/'.$it->getSubPathName();

                    /*** the new file name ***/
                    $new_file = $directory.'/'.$it->getSubPath().'/'.safe_names($it->current());
                    
                    /*** rename the file ***/
                    rename ($old_file, $new_file);

                    /*** a little message to say file is converted ***/
                    echo 'Renamed '. $directory.'/'.$it->getSubPathName() ."\n";
                }
            }
            /*** move to the next iteration ***/
            $it->next();
        }
        
        /*** when we are all done let the user know ***/
        echo 'Renaming of files complete'."\n";
    }
    catch(Exception $e)
    {
        echo $e->getMessage()."\n";
    }
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.