Jump to content


Photo

PHP file renaming script


  • Please log in to reply
3 replies to this topic

#1 Moon-Man.net

Moon-Man.net
  • Members
  • PipPipPip
  • Advanced Member
  • 84 posts

Posted 04 September 2006 - 01:58 AM

Hey forum,
Could someone please give me a hand to write a script that will go through any given folder in a linux system, and remove BAD charactures? We have some macs that need to move files accross to a Samba inviroment, and it forbidds these cahractures. "\/ : * ? " < > |" but there are about 10,000 files that need to be renamed! Im not gonna do all them  :o
The only issue is that it needs to be a reocursive script. And that part im lost on :S
Could someone please help?
Cheers,
Nathan

#2 ToonMariner

ToonMariner
  • Members
  • PipPipPip
  • Advanced Member
  • 3,342 posts
  • LocationNewcastle upon Tyne, UK

Posted 04 September 2006 - 02:02 AM

OK msn me toonmariner(at)hotmail.com
follow me on twitter @PHPsycho

#3 Moon-Man.net

Moon-Man.net
  • Members
  • PipPipPip
  • Advanced Member
  • 84 posts

Posted 04 September 2006 - 02:58 AM

Can anyone else offer some help?
Cheers,
Nathan

#4 Jenk

Jenk
  • Members
  • PipPipPip
  • Advanced Member
  • 778 posts

Posted 04 September 2006 - 09:38 AM

<?php
$dir = '/path/to/old/dir';
$handle = opendir($dir);

while(($file = readdir($handle)) !== false) 
{
    if (preg_match('/' . preg_quote('\/ : * ? " < > |', '/') . '/', $file))
    {
        $path = $dir . DIRECTORY_SEPARATOR . $file;
        if (!in_array($file, array('..', '.')) && is_file($path)) 
        {
            $contents = file_get_contents($path);
            $newPath = $dir . DIRECTORY_SEPARATOR . preg_replace('/' . preg_quote('\/ : * ? " < > |', '/') . '/', '_', $file);
            if (file_put_contents($newPath, $contents) !== false) 
            {
                $unlink($path); //delete old file only if able to create new
            }
        }
    }
}
?>





0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users