Home >> Hobbies >> PHP Programming  

Hobbies --> PHP Programming

Removing CTRL-M Characters

I do a lot of cross-platform coding.  For example, I'll develop a new application on my personal website, then transfer the scripts to my Linux box at work.  When editing files with Windows, CTRL-M characters are inserted at the end of each line are become visibile when editing with Linux.  While PHP doesn't care about the extra characters, sometimes I just don't want to see them.  Previously, I'd use the vi editor to remove them by executing the following command %s/CTRL-V CTRL-M//g.  But, I recently had a large application that had over 30 PHP files that I had to convert.  So, I wrote the following script to batch process all PHP files within a given directory.

<?php
// note that ctrl+M (in vim known as ^M) is hexadecimally 0x0D
// array of characters to convert
$trans = array("\x0D" => "");
// let's populate the a list of php files to process
$directory = "/var/www/html/php/dirname/";
$filelist = array();
if (!($filehandle = opendir($directory))) die("Cannot open $directory");
 { while($file = readdir($filehandle))
    { if (ereg("\.php", $file))
       { $trimmed = rtrim($file);
         $file_count = array_push ($filelist, $trimmed);
       }
    }
    closedir($filehandle);
    rsort($filelist);
  }
// now, let's loop through the file list, read the contents of each file
// into an array, convert the characters, and rewrite the file.
for ($a=0; $a<$file_count; $a++)
 { $filename = $directory . $filelist[$a];
   echo "processing $filename\n";
   $lines = file($filename);
   $handle = fopen($filename,"w");
   for ($b=0; $b<count($lines); $b++)
    { $newline = strtr($lines[$b],$trans);
      fwrite($handle,$newline);
    }
      fclose($handle);
  }
?>

It would be best to execute this script from the command line instead of within an Internet browser.  This is due to the fact that the directory and files would need need to have permissions of 777 in order for the script to proceed in a web browser.
 


Home >> Hobbies >> PHP Programming

webmaster at vansvault dot org

Last modified: February 20, 2006