Jump to content

removing extra spaces/line breaks to reduce file size


liamoco

Recommended Posts

Hi, I want to remove all extra spaces and line breaks that I have in my PHP, HTML, CSS and JavaScript files, to reduce the file size, I do not want to go through 100+ files and do this manually. Is there a PHP script that would do this? Any suggestions where I should start looking?

 

Thanks

Hello there Liamoco, try the following.

 

<?php
  // Set Filename could use a "$_GET" variable here
  $fileName = 'file.php';
  //Get the contents of the file
  $fileContents = file_get_contents($fileName);
  // Remove any comments from the contents of the file
  $reformatFile = preg_replace('/#.*/','',preg_replace('#//.*#','',preg_replace('#/\*(?:[^*]*(?:\*(?!/))*)*\*/#','',($fileContents))));
  // A little wizardry to remove whitespace but always keep at least 1
  $reformatFile = preg_replace('/\s+/', ' ', $reformatFile);

  // Create a new file with the code in it
  $newFile = fopen($fileName, 'w');
  fwrite($newFile, $reformatFile);
  fclose($newFile)

  // Create a file with old code just incase it breaks
  $oldFile = fopen('_'.$fileName, 'w');
  fwrite($oldFile, $fileContents);
  fclose($oldFile);
?>

 

Appropriate commenting is within the file :)

 

Tell me how it goes bud.

 

Regards, Paul.

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.