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

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.