REGEX: comment supprimer des commentaires de javascripts, en utilisant le code PHP

je suis en train de combiner tout mon javasrupt en un seul fichier neat afin de réduire les requêtes http! Im stuck suppression des commentaires /* comments */ et // comments . Mon niveau est bien en dessous de la minification ou de l'analyse. Je sais comment faire des macaronis cordes. Rien de plus complexe que cela, vous ne trouverez pas dans mon ordinateur ou cuisine, donc:

QUESTION

en attendant à la combinaison à un dossier, je veux supprimer tous les commentaires.

Quel est le regex correct pour cela?

<?php
header('Content-type: text/javascript');    
$offset = 60 * 60 * 24; // Cache for a day
header ('Cache-Control: max-age=' . $offset . ', must-revalidate');
header ('Expires: ' . gmdate ("D, d M Y H:i:s", time() + $offset) . ' GMT');

ob_start("compress");
function compress($buffer) {

# NOT SURE, not all new lines are removed??
# remove tabs, spaces, newlines, etc.
$buffer = str_replace(array("rn", "r", "t", '  ', '    '), '', $buffer);  

# WORKS !!!
# remove comments / XXXXXXX
$buffer = preg_replace('(// .+)', '', $buffer);

######################################################################## 
# !! STUCK HERE !! OUTPUT FILE LOOKS OK BUT WEBSITE DOESNT LOAD OK IF THIS IS ON
# remove comments / * XXX  (enters etc) XXXX  * /
# $buffer = preg_replace('#/*(?:.(?!/)|[^*](?=/)|(?<!*)/)**/#s', '', $buffer);
########################################################################        

return $buffer;
}

include('../file1.js');
include('../file2.js');  
ob_end_flush();
?>

Ce serait formidable si elle allait attraper et de supprimer le texte suivant:

/* XXXX */

/* 
  XXXX
  XXXX
*/

C'est tout! Je ne peux pas le faire fonctionner nomatter ce regex que j'utilise même avec cet outil incroyable, où j'ai trouvé la bonne correspondance pour être:

RegExp: //*(?:.(?!/)|[^*](?=/)|(?<!*)/)**//gs
pattern: /*(?:.(?!/)|[^*](?=/)|(?<!*)/)**/
flags: gs

http://gskinner.com/RegExr /

2
demandé sur Sam 2010-12-10 10:14:03

4 réponses

L'utilisation d'expressions régulières n'est pas le moyen le plus efficace de supprimer les commentaires Javascript. Vous avez besoin d'un analyseur de ficelles et d'une minifieuse. Voir http://razorsharpcode.blogspot.com/2010/02/lightweight-javascript-and-css.html

si vous insistez sur les modèles regex, pensez à la façon dont vous analyseriez ce code simple qui ne contient aucun commentaire Javascript:

var regex=/(ftp|https?):\/\//; alert('hello, world'); return regex;

notez la double barre oblique avant alert() . Un l'analyseur stupide qui utilise des expressions régulières traitera le code Javascript valide comme des commentaires!

7
répondu stillstanding 2014-01-02 00:54:20

je voudrais partager un extrait de code regex (PHP) J'ai écrit pour moi-même il est également utilisé dans le Yireo sriptmerge plugin pour joomla marqué comme code simple.. Pour compresser le code javascript et supprimer tous les commentaires. Il fonctionne également avec mootools il est rapide (par rapport à D'autres solutions PHP) et n'endommage pas le JavaScript lui - même et il résout beaucoup de problèmes de suppression de commentaires.

//--------------------------------------------------------------------------------------------------------- 
//Just started with it!
//Prototype Still working at it when ever I got time by patient please? Tested on 800.000 lines of code!
// Finished it 800.000 lines remove javascript comments without error....16-01-2016
// Its not bullentproof but chances are its gonna work for you...
//----------------------------------------------------------------//-------- //------------------------------------------------------------------------------
//--------------------------------------------------------------------------
//These are 112 lines off code that work together also works with mootools and Joomla and drupal and other cms websites. 
//Tested it on 800.000 lines of code and comments. works fine. 
//This one selects multiple parenthetical like with comments between colons ( abc(/*nn*/('/*xvx*/'))"// testing line") and protect them.
//16-01-2016..! This is the code with the comments in it.!!!!    
//----------------------------------------------------------------//-----------------------------------------
$buffer = preg_replace("/(\*\/\s*)\/\/(?!(\*\/|[^\r\n]*?[\\n\\r]+\s*\"\s*\+|[^\r\n]*?[\\n\\r]+\s*\'\s*\+))[^\n\r\;]*?[^\;]\s*[\n\r]/", "\n", $buffer);
do {$buffer = preg_replace("/(http(s)?\:)([^\r\n]*?)(\/\/)/", "qDdXX", $buffer, 1, $count);} while ($count);
do {$buffer = preg_replace("/(^^\s*\/)(\/).*/", "\n", $buffer, 1, $count);} while ($count);
$buffer = preg_replace("/([\r\n]+?\s*|\,\s*|\;\s*|\|\s*|\)\s*|\+\s*|\&\s*|\{\s*|\}\s*|\]\s*|\[\s*|\+\s*|\'\s*|\"\s*|\:\s*|-\s*)((\/)(\/)+)([^\r\n\'\"]*?[nte]'[a-z])*?(?!([^\r\n]*?)([\'\"]|[\\]|\*\/|[=]+\s*\";|[=]+\s*\';)).*/", "\n", $buffer);
$buffer = preg_replace("/(^^\s*\/\*)(?!([\'\"]))[\s\S]*?(\*\/)/", "\n \n", $buffer);    
$buffer = preg_replace("/(\|\|\s*|=\s*|[\n\r]|\;\s*|\,\s*|\{\s*|\}\s*|\+\s*|\?\s*)((?!([\'\"]))\/\*)(?!(\*\/))[\s\S]*?(\*\/)/", "\n", $buffer);
$buffer = preg_replace("/(\;\s*|\,\s*|\{\s*|\}\s*|\+\s*|\?\s*|[\n\r]\s*)((?!([\'\"]))\/\*)(?!(\*\/))[\s\S]*?(\*\/)/", "\n", $buffer);
//Remove: ) /* non-empty*//*xxx*/)
do {$buffer = preg_replace('/([^\/\"\'\*a-zA-Z0-9\>])\/\*(?!(\*\/))[^\n\r@]*?\*\/(?=([\/\"\'\\\*a-zA-Z0-9\>\s=\)\(\,:;\.\}\{\|\]\[]))/', "", $buffer, 1, $count);} while ($count); 
$buffer = preg_replace("/([\;\n\r]\s*)\/\/.*/", "\n", $buffer);   
$buffer = preg_replace("/(\/\s\/)([g][\W])/", "ZUQQ", $buffer);
$buffer = preg_replace("/\\n/", "AQerT", $buffer);
$buffer = preg_replace("/\\r/", "BQerT", $buffer);    
////---------------------------------------------------------------------------------------------------------
// Remove all extra new lines after [ and \
$buffer = preg_replace("/([^\*])(\*|[\r\n]|\'|\"|\,|\+|\{|;|\(|\)|\[|\]|\{|\}|\?|[^p|s]:|\&|\%|[^\\][a-m-o-u-s-zA-Z]|\||-|=|[0-9])(\s*)(?!([^=\\\&\/\"\'\^\*:]))(\/)(\/)+(?!([\r\n\*\+\"]*?([^\r\n]*?\*\/|[^\r\n]*?\"\s*\+|([^\r\n]*?=\";))))([^\n\r]*)([^;\"\'\{\(\}\,]\s*[\\\[])(?=([\r\n]+))/", "", $buffer);

// /* followed by (not new line but) ... */ ... /* ... till */
$buffer = preg_replace("/((([\r\n]\s*)(\/\*[^\r\n]*?\*\/(?!([^\n\r]*?\"\s*\+)))([^\n\r]*?\/\*[^\n\r]*?\*\/(?!([^\n\r]*?\"\s*\+))[^\n\r]*?\/\*[^\n\r]*?\*\/(?!([^\n\r]*?\"\s*\+)))+)+(?!([\*]))(?=([^\n\r\/]*?\/\/\/)))/", "", $buffer);
// (slash slash) remove everything behinde it not if its followed by */ and /n/r or " + and /n/r
$buffer = preg_replace("/([\r\n]+?\s*)((\/)(\/)+)(?!([^\r\n]*?)([\\]|\*\/|[=]+\s*\";|[=]+\s*\';)).*/", "\n", $buffer);
// slash slash star between collons protect like: ' //* ' by TDdXX
$buffer = preg_replace("/(\'\s*)(\/\/\*)([^\r\n\*]*?(?!(\*\/))(\'))/", "TDdXX", $buffer); 
// slash slash star between collons protect like: " //* " by TDdXX
$buffer = preg_replace("/(\"\s*)(\/\/\*)([^\r\n\*]*?(?!(\*\/))(\"))/", "TDdXX", $buffer); 
// slash slash star between collons protect like: ' //* ' by TDdXX
$buffer = preg_replace("/(\'\s*)(\/\*)([^\r\n\*]*?(?!(\*\/))(\'))/", "pDdYX", $buffer); 
// slash slash star between collons protect like: " //* " by TDdXX
$buffer = preg_replace("/(\"\s*)(\/\*)([^\r\n\*]*?(?!(\*\/))(\"))/", "pDdYX", $buffer);
// in regex star slash protect by: ODdPK
$buffer = preg_replace("/(\,\s*)(\*\/\*)(\s*[\}\"\'\;\)])/", "RDdPK", $buffer); // , */* '
$buffer = preg_replace('/(\n|\r|\+|\&|\=|\|\||\(|[^\)]\:[^\=\,\/$\\\<]|\(|return(?!(\/[a-zA-Z]+))|\!|\,)(?!(\s*\/\/|\n))(\s*\/)([^\]\)\}\*\;\,gi\.]\s*)([^\/\n]*?)(\*\/)/', 'ODdPK', $buffer); 
//// (slash r) (slash n) protect if followed by " + and new line
$buffer = preg_replace("/[\/][\/]+(AQerTBQerT)(\s*[\"]\s*[\+])/", "WQerT", $buffer);
$buffer = preg_replace("/[\/][\/]+(\*\/AQerTBQerT)(\s*[\"]\s*[\+])/", "YQerT", $buffer);
// Html Text protection!
$buffer = preg_replace("/([\r\n]\s*\/\/)[^\r\n]*?\/\*(?=(\/))[^\r\n]*?([\r\n])/", " */", $buffer);
$buffer = preg_replace("/([\)]|[^\/|\\|\"])(\/\*)(?=([^\r\n]*?[\\][rn]([\\][nr])?\s*\"\s*\+\s*(\n|\r)?\s*\"))/", "pDdYX", $buffer);
$buffer = preg_replace('/([\"]\s*[\,\+][\r\n]\s*[\"])(\s*\/\/)((\/\/)|(\/))*/', 'qDdXX', $buffer);
$buffer = preg_replace('/([\"]\s*[\,\+][\r\n]\s*[\"](qDdXX))[\\]*(\s*\/\/)*((\/\/)|(\/))*/', '', $buffer);
// started by new line slash slash remove all not followed by */ and new line!
$buffer = preg_replace("/([\r\n]\s*)(?=([^\r\n\*\,\:\;a-zA-Z\"]*?))(\/)+(\/)[^\r\n\/][^\r\n\*\,]*?[\*]+(?!([^\r\n]*?(([^\r\n]*?\/|\"\s*\)\s*\;|\"\s*\;|\"\s*\,|\'\s*\)\s*\;|\'\s*\;|\'\s*\,))))[^\r\n]*(?!([\/\r\n]))[^\r\n]*/", "", $buffer);
// removes all *.../ achter // leaves the ( // /* staan en */ ) 1 off 2
$buffer = preg_replace("/([\r\n](\/)*[^:\;\,\.\+])(\/\/[^\r\n]*?)(\*)?([^\r\n]+?)(\*)+([^\r\n\*\/])+?(\/[^\*])(?!([^\r\n]*?((\"\s*\)\s*\;|\"\s*\;|\"\s*\,|\'\s*\)\s*\;|\'\s*\;|\'\s*\,))))/", "", $buffer);
// removes all /* after // leaves the ( // */ staan ) 2 off 2
do {$buffer = preg_replace("/([\r\n])((\/)*[^:\;\,\.\+])(\/\/[^\r\n]*?)(\*)?([^\r\n]+?)(\/|\*)([^\r\n]*?)(\*)[\r\n]/", "", $buffer, 1, $count);} while ($count); 
////---------------------------------------------------------------------------------------------------------
// removes all (/* and */) combinations after // and everything behinde it! but leaves  ///* */ or example. ///*//*/ one times.
$buffer = preg_replace("/(((([\r\n](?=([^:;,\.\+])))(\/)+(\/))(\*))([^\r\n]*?)(\/\*)*([^\r\n])*?(\*\/)(?!([^\r\n]*?((\"\s*\)\s*\;|\"\s*\;|\"\s*\,|\'\s*\)\s*\;|\'\s*\;|\'\s*\,))))(((?=([^:\;\,\.\+])))(\/)*([^\r\n]*?)(\*|\/)?([^\r\n]*?)(\/\*)([^\r\n])*?(\*\/)(?!([^\r\n]*?((\"\s*\)\s*\;|\"\s*\;|\"\s*\,|\'\s*\)\s*\;|\'\s*\;|\'\s*\,)))))*)+[^\r\n]*/", "", $buffer);
// removes /* ... followed by */ repeat even pairs till new line!
$buffer = preg_replace("/(\/\*[\r\n]\s*)(?!([^\/<>;:%~`#@&-_=,\.$\^\{\[\(\|\)\*\+\?\'\"\a-zA-Z0-9]))(((\/\*)[^\r\n]*?(\*\/)?[^\r\n]*?(\/\*)[^\r\n]*?(\*\/))*((\/\*)[^\r\n]*?(\*\/)))+(?!([^\r\n]*?(\*\/|\/\*)))[^\r\n]*?[\r\n]/", "\n", $buffer);
////---------------------------------------------------------------------------------------------------------
// (Mark) Regex Find all "  Mark with = AwTc  and  CwRc // special cahacers are:  . \ + * ? ^ $ [ ] ( ) { } < > = ! | : " '
$buffer = preg_replace("/(?!([\r\n]))([^a-zA-Z0-9]\+|\?|&|\=|\|\||\!|\(|,|return(?!(\/[a-zA-Z]+))|[^\)]\:)(?!(\s*\/\/|\n|\/\*[^\r\n\*]*?\*\/))(\s*\/([\*\^]?))(?!([\r\n\*\/]|[\*]))(?!(\<\!\-\-))(([^\^\]\)\}\*;,g&\.\"\']?\s*)(?=([\]\)\}\*;,g&\.\/\"\']))?)(([^\r\n]*?)(([\w\W])([\*]?\/\s*)(\})|([^\\])([\*]?\/\s*)(\))|([\w\W])([\*]?\/\s*)([i][g]?[\W])|([\w\W])([\*]?\/\s*)([g][i]?[\W])|([\w\W])([\*]?\/\s*)(?=(\,))|([^\\]|[\/])([\*]?\/\s*)(;)|([\w\W])([\*]?\/\:\s)(?!([@\]\[\)\(\}\{\.,#%\+-\=`~\*&\^;\:\'\"]))|([^\\])([\*]?\/\s*)(\.[^\/])|([^\\])([\*]?\/\s*)([\r\n]\s*[;\.,\)\}\]]\s*[^\/]|[\r\n]\s*([i][g]?[\W])|[\r\n]\s*([g][i]?[\W])))|([^\\])([\*]?\/\s*)([;\.,\)\}\]]\s*[^\/]|([i][g]?[\W])|([g][i]?[\W])))/", "AwTcCwRc", $buffer);


// Remove all extra new lines after [ and \
$buffer = preg_replace("/([^;\"\'\{\(\}\,\/]\s*[^\/][\\\[]\s?)\s*([\r\n]+)/", "", $buffer); 
$buffer = preg_replace("/([\|\[])\s*([\|\]])/", "", $buffer);
// (star slash) or (slash star) 1 sentence! Protect! With pDdYX and ODdPK
do {$buffer = preg_replace('/(AwTc)([^\r\nC]*?)(\/\*)(?=([^\r\n]*?CwRc))/', 'pDdYX', $buffer, 1, $count);} while ($count);
do {$buffer = preg_replace('/(AwTc)([^\r\nC]*?)(\*\/)(?=([^\r\n]*?CwRc))/', 'ODdPK', $buffer, 1, $count);} while ($count);
// (slash slash) 1 sentence! Protect with: qDdXX
do {$buffer = preg_replace('/(AwTc)([^\r\nC]*?)(\/\/)(?=([^\r\n]*?CwRc))/', 'qDdXX', $buffer, 1, $count);} while ($count); 

//---------------------------------------------------------------------------------------------------------
// DEZE WERKT !! multiple parentheticals counting for even ones!
 $buffer = preg_replace("/([^\(\/\"\']\s*)(?!\(\s*function)((\()(?=([^\n\r\)]*?[\'\"]))(?!([^\r\n]*?\"\s*\<[^\r\n]*?\>\s*\"|[^\r\n]*?\"\s*\\\s*\"|[^\r\n]*?\"\s*\[[^\r\n]*?\]\s*\"))((?>[^()]+)|(?2))*?\))(?!(\s*\"\s*\;|\s*\'\s*\;|\s*\/|\s*\)|\s*\"|[^\n\r]*?\"\s*\+\s*(\n|\r)?\s*\"))/", " /*Yu*/  /*Zu*/ ", $buffer);

// this one is  SINGLE parentheticals pair.
//     $buffer = preg_replace("/([^\(\/\"\']\s*)((\()(?=([^\n\r\)]*?[\'\"]))(?!(function|\)|[^\r\n]*?\"\s*\+[^\r\n]*?\+\s*\"|[^\r\n]*?\"\s*\<[^\r\n]*?\>\s*\"|[^\r\n]*?\"\s*\\\s*\"|[^\r\n]*?\"\s*\[[^\r\n]*?\]\s*\"))([^()]*?\)))(?!(\s*\"\s*\;|\s*\'\s*\;|\s*\/|\s*\)|\s*\"|[^\n\r]*?\"\s*\+\s*(\n|\r)?\s*\"))/", " /*Yu*/  /*Zu*/ ", $buffer); 

// (slash slash) 1 sentence! Protect with: qDdXX
do {$buffer = preg_replace('/(\/\*Yu\*\/)([^\r\n]*?)(\/)(\/)(?=([^\r\n]*?\/\*Zu\*\/))/', 'qDdXX', $buffer, 1, $count);} while ($count); 
do {$buffer = preg_replace("/(\/\*Yu\*\/)([^\n\r\'\"]*?[\"\'])([^\n\r\)]*?)(\/\*)([^\n\r\'\"\)]*?[\"\'])([^\n\r]*?\/\*Zu\*\/)/", "pDdYX", $buffer, 1, $count);} while ($count);
do {$buffer = preg_replace("/(\/\*Yu\*\/)([^\n\r\'\"]*?[\"\'])([^\n\r\)]*?)(\*\/)([^\n\r\'\"\)]*?[\"\'])([^\n\r]*?\/\*Zu\*\/)/", "ODdPK", $buffer, 1, $count);} while ($count);

//---------------------------------------------------------------------------------------------------------
// (slash slash) 2 sentences! Protect ' and "
do {$buffer = preg_replace("/(=|\+|\(|[a-z]|\,)(\s*)(\")([^\r\n\;\/\'\)\,\]\}\*]*?)(\/)(\/)([^\r\n\;\"\*]*?)(\")/", "qDdXX", $buffer, 1, $count);} while ($count);
do {$buffer = preg_replace("/(=|\+|\(|[a-z]|\,)(\s*)(\')([^\r\n\;\/\'\)\,\]\}\*]*?)(\/)(\/)([^\r\n\*\;\']*?)(\')/", "qDdXX", $buffer, 1, $count);} while ($count); 
// (slash slash) 2 sentences! Protect slash slash between ' and "
do {$buffer = preg_replace("/(\"[^\r\n\;]*?)(\/)(\/)([^\r\n\"\;]*?([\"]\s*(\;|\)|\,)))/", "qDdXX", $buffer, 1, $count);} while ($count); 
do {$buffer = preg_replace("/(\'[^\r\n\;]*?)(\/)(\/)([^\r\n\'\;]*?([\']\s*(\;|\)|\,)))/", "qDdXX", $buffer, 1, $count);} while ($count); 
//---------------------------------------------------------------------------------------------------------
// Remove all slar slash achter \n
$buffer = preg_replace("/([\n\r])([^\n\r\*\,\"\']*?)(?=([^\*\,\:\;a-zA-Z\"]*?))(\/)(\/)+(?=([^\n\r]*?\*\/))([^\n\r]*?(\*\/)).*/", " ", $buffer); 
do {$buffer = preg_replace("/([\r\n]\s*)((\/\*(?!(\*\/)))([^\r\n]+?)(\*\/))(?!([^\n\r\/]*?(\/)(\/)+\*))/", "", $buffer, 1, $count);} while ($count);
$buffer = preg_replace("/([\n\r]\/)(\/)+([^\n\r]*?)(\*\/)([^\n\r]*?(\*\/))(?!([^\n\r]*?(\*\/)|[^\n\r]*?(\/\*))).*/", "/ ", $buffer);  
do {$buffer = preg_replace("/([\n\r]\s*\/\*\*\/)([^\n\r=]*?\/\*[^\n\r]*?\*\/)(?=([\n\r]|\/\/))/", "", $buffer, 1, $count);} while ($count); 
$buffer = preg_replace("/([\n\r]\s*\/\*\*\/)([^\n\r=]*?)(\/\/.*)/", "", $buffer); 
// Remove all slash slash achter = '...'; //......
do {$buffer = preg_replace("/(\=\s*)(?=([^\r\n\'\"]*?\'[^\n\r\']*?\'))([^\n\r;]*?[;]\s*)(\/\/[^\r\n][^\r\n]*)[\n\r]/", "", $buffer, 1, $count);} while ($count);
// protect slash slash '...abc//...abc'!
do {$buffer = preg_replace("/(\=)(\s*\')([^\r\n\'\"]*?)(\/)(\/)([^\r\n]*?[\'])/", "qDdXX", $buffer, 1, $count);} while ($count);
//(slash star) or (star slash) : no dubble senteces here! Protect with: pDdYX and ODdPK
do {$buffer = preg_replace("/(\"[^\r\n\;\,\"]*?)(\/)(\*)(?!([YZ]u\*\/))([^\r\n;\,\"]*?)(\")/", "pDdYX", $buffer, 1, $count);} while ($count);   // open
do {$buffer = preg_replace("/([^\"]\"[^\r\n\;\/\,\"]*?)(\s*)(\*)(\/)([^\r\n;\,\"=]*?)(\")/", "ODdPK", $buffer, 1, $count);} while ($count); // close
do {$buffer = preg_replace("/(\'[^\r\n\;\,\']*?)(\/)(\*)(?!([YZ]u\*\/))([^\r\n;\,\']*?)(\')/", "pDdYX", $buffer, 1, $count);} while ($count);   // open
do {$buffer = preg_replace("/(\'[^\r\n\;\/\,\']*?)(\s*)(\*)(\/)([^\r\n;\,\']*?)(\')/", "ODdPK", $buffer, 1, $count);} while ($count); // close
// protect star slash '...abc*/...abc'!
do {$buffer = preg_replace("/(\'[^\r\n\;\,\']*?)(\*)(\/)([^\r\n;\,\']*?)(\')(?!([^\n\r\+]*?[\']))/", "ODdPK", $buffer, 1, $count);} while ($count); 
// protect star slash '...abc*/...abc'!
do {$buffer = preg_replace("/(\"[^\r\n\;\,\"]*?)(\*)(\/)([^\r\n;\,\"]*?)(\")(?!([^\n\r\+]*?[\"]))/", "ODdPK", $buffer, 1, $count);} while ($count);
 //---------------------------------------------------------------------------------------------------------
//// \n protect
do {$buffer = preg_replace("/(=\s*\"[^\n\r\"]*?)(\/\/)(?=([^\n\r]*?\"\s*;))/", "qDdXX", $buffer, 1, $count);} while ($count); 
do {$buffer = preg_replace("/(=\s*\"[^\n\r\"]*?)(\/\*)(?!([YZ]u\*\/))(?=([^\n\r]*?\"\s*;))/", "pDdYX", $buffer, 1, $count);} while ($count); 
do {$buffer = preg_replace("/(=\s*\"[^\n\r\"]*?)(\*\/)(?=([^\n\r]*?\"\s*;))/", "ODdPK", $buffer, 1, $count);} while ($count); 
do {$buffer = preg_replace("/(=\s*\'[^\n\r\']*?)(\/\/)(?=([^\n\r]*?\'\s*;))/", "qDdXX", $buffer, 1, $count);} while ($count); 
do {$buffer = preg_replace("/(=\s*\'[^\n\r\']*?)(\/\*)(?!([YZ]u\*\/))(?=([^\n\r]*?\'\s*;))/", "pDdYX", $buffer, 1, $count);} while ($count); 
do {$buffer = preg_replace("/(=\s*\'[^\n\r\']*?)(\*\/)(?=([^\n\r]*?\'\s*;))/", "ODdPK", $buffer, 1, $count);} while ($count); 
//---------------------------------------------------------------------------------------------------------
// (Slash Slash) alle = " // " and = ' // ' replace by! qDdXX
do {$buffer = preg_replace("/(\=|\()(\s*\")([^\r\n\'\"]*?[\'][^\r\n\'\"]*?)(\/)(\/)([^\r\n\'\"]*?[\'])(\s*\'[^\r\n\'\"]*?)(\/\/|qDdXX)?([^\r\n\'\"]*?[\'][^\r\n\'\"]*?[\"])(?!(\'\)|\s*[\)]?\s*\+|\'))/", "qDdXXqDdXX", $buffer, 1, $count);} while ($count); 
do {$buffer = preg_replace("/(\=|\()(\s*\')([^\r\n\'\"]*?[\"][^\r\n\'\"]*?)(\/)(\/)([^\r\n\'\"]*?[\"])(\s*\"[^\r\n\'\"]*?)(\/\/|qDdXX)?([^\r\n\'\"]*?[\"][^\r\n\'\"]*?[\'])(?!(\'\)|\s*[\)]?\s*\+|\'))/", "qDdXXqDdXX", $buffer, 1, $count);} while ($count); 
//---------------------------------------------------------------------------------------------------------
// (slash slash) Remove all also , or + not followed by */ and newline
$buffer = preg_replace("/([^\*])(\*|[\r\n]|[^\\]\'|[^\\]\"|\,|\+|\{|;|\(|\)|\[|\]|\{|\}|\?|[^p|s]:|\&|\%|[^\\][a-m-o-u-s-zA-Z]|\||-|=|[0-9])(\s*)(?!([^=\\\&\/\"\'\^\*:]))(\/)(\/)+(?!([\r\n\*\+\"]*?([^\r\n]*?\*\/|[^\r\n]*?\"\s*\+|([^\r\n]*?=\";)))).*/", "", $buffer);
// (slash slash star slash) Remove everhing behinde it not followed by */ or new line
$buffer = preg_replace("/(\/\/\*\/)(?!([\r\n\*\+\"]*?([^\r\n]*?\*\/|[^\r\n]*?\"\s*\+|([^\r\n]*?=\";)))).*/", "", $buffer);
// Remove almost all star comments except colon/**/
$buffer = preg_replace("/(?!([^\n\r]*?[\'\"]))(\s*<!--.*-->)(?!(<\/div>))[^\n\r]*?.*/","", $buffer);
$buffer = preg_replace("/([\n\r][^\n\r\*\,\"\']*?)(?=([^\*\,\:\;a-zA-Z\"]*?))(\/)(\/)+(?!([\r\n\*\+\"]*?([^\r\n]*?\*\/|[^\r\n]*?\"\s*\+|([^\r\n]*?=\";)))).*/", "", $buffer);
$buffer = preg_replace("/(?!([^\n\r]*?[\'\"]))(\s*<!--.*-->)(?!(<\/div>))[^\n\r]*?(\*\/)?.*/","", $buffer);
$buffer = preg_replace("/(<!--.*?-->)(?=(\s*<\/div>))/","", $buffer);
//---------------------------------------------------------------------------------------------------------
// Restore all
$buffer = preg_replace("/qDdXX/", "//", $buffer);  // Restore //
$buffer = preg_replace("/pDdYX/", "/*", $buffer);   // Restore 
$buffer = preg_replace("/ODdPK/", "*/", $buffer);   // Restore 
$buffer = preg_replace("/RDdPK/", "*/*", $buffer);   // Restore 
$buffer = preg_replace("/TDdXX/", "//*", $buffer);   // Restore */
$buffer = preg_replace('/WQerT/', '\\r\\n" +', $buffer);   // Restore \r\n" + 
$buffer = preg_replace('/YQerT/', '//*/\\r\\n" +', $buffer);   // Restore \r\n" + 
$buffer = preg_replace('/AQerT/', '\\n', $buffer);   // Restore \n" 
$buffer = preg_replace('/BQerT/', '\\r', $buffer);   // Restore \r"
$buffer = preg_replace("/ZUQQ/", "/ /", $buffer);
$buffer = preg_replace('/\s\/\*Zu\*\/\s/', '', $buffer);   // Restore \n"
$buffer = preg_replace('/\s\/\*Yu\*\/\s/', '', $buffer);   // Restore \n"
////---------------------------------------------------------------------------------------------------------
//// Remove all markings!
$buffer = preg_replace('/(AwTc)/', '', $buffer);  // Start most Regex!
$buffer = preg_replace('/(CwRc)/', '', $buffer);  // End Most regex!
// all \s and [\n\r] repair like they where!
$buffer = preg_replace("/([a-zA-Z0-9]\s?)\s*[\n\r]+(\s*[\)\,&]\s?)(\s*[\r\n]+\s*[\{])/", "", $buffer); 
$buffer = preg_replace("/([a-zA-Z0-9\(]\s?)\s*[\n\r]+(\s*[;\)\,&\+\-a-zA-Z0-9]\s?)(\s*[\{;a-zA-Z0-9\,&\n\r])/", "", $buffer); 
$buffer = preg_replace("/(\(\s?)\s*[\n\r]+(\s*function)/", "", $buffer);
$buffer = preg_replace("/(=\s*\[[a-zA-Z0-9]\s?)\s*([\r\n]+)/", "", $buffer); 
//-----------------------------------------------
$buffer = preg_replace("/([^\*\/\'\"]\s*)(\/\/\s*\*\/)/", "", $buffer);
//// Remove all /**/// .... Remove expept /**/ and followed by */ till newline!
$buffer = preg_replace("/(\/\*\*\/)(\/\/(?!([^\n\r]*?\*\/)).*)/", "", $buffer);
$buffer = preg_replace("/(\;\/\*\*\/)(?!([^\n\r]*?\*\/)).*/", "", $buffer);
$buffer = preg_replace("/(\/\/\\\*[^\n\r\"\'\/]*?[\n\r])/", "\r\n", $buffer);
$buffer = preg_replace("/([\r\n]\s*)(\/\*[^\r\n]*?\*\/(?!([^\r\n]*?\"\s*\+)))/", "", $buffer);
//Remove colon /**/
$buffer = preg_replace("/\/\*\*\/\s/", " ", $buffer);
$buffer = preg_replace("/(\=\s*)(?=([^\r\n\'\"]*?\'[^\n\r\'\"]*?\'))([^\n\r\/]*?)(\/\/[^\r\n\"\'][^\r\n]*[\'\"])(\/\*\*\/)[\n\r]/", "\n", $buffer);
$buffer = preg_replace("/(\=\s*)(?=([^\r\n\'\"]*?\"[^\n\r\'\"]*?\"))([^\n\r\/]*?)(\/\/[^\r\n\"\'][^\r\n]*[\'\"])(\/\*\*\/)[\n\r]/", "\n", $buffer);
//Remove colon //
$buffer = preg_replace("/([^\'\"ps\s]\s*)(\:[^\r\n\'\"\[\]]*?\'[^\n\r\'\"]*?\')([^\n\r\/a-zA-Z0-9]*?)(\/\/)[^\r\n\/\'][^\r\n]*/", "", $buffer);
$buffer = preg_replace("/([^\'\"ps\s]\s*)(\:[^\r\n\'\"\[\]]*?\"[^\n\r\'\"]*?\")([^\n\r\/a-zA-Z0-9]*?)(\/\/)[^\r\n\/\"][^\r\n]*/", "", $buffer);
$buffer = preg_replace("/(\"[^\n\r\'\"\+]*?\")([^\n\r\/a-zA-Z0-9]*?)(\/\/)(?!(\*|[^\r\n]*?[\\n\\r]+\s*\"\s*\+|[^\r\n]*?[\\n\\r]+\s*\'\s*\+))[^\r\n\/\"][^\r\n]*/", "", $buffer);
//Remove all after ; slah slah+
$buffer = preg_replace("/(;\s*)\/\/(?!([^\n\r]*?\"\s*;)).*/", " \n", $buffer);
//Remove: ) /* non-empty*//*xxx*/)
$buffer = preg_replace('/([\n\r][^\n\r\"]*?)([^\/\"\'\*\>])\/\*(?!(\*\/))[^\n\r\"]*?[^@]\*\//', "", $buffer);
//Remove // vooraf gegaan door: || | ? | , //
$buffer = preg_replace("/(\|\||[\?]|\,)(\s*)\/\/(?!([^\n\r]*?\*\/|\"|\')).*/", "", $buffer);
//Remove: [\n\r] after: [ \|\[\;\,\:\=\-\{\}\]\[\?\)\( ]
$buffer = preg_replace("/([\|\[\;\,\:\=\-\{\}\]\[\?\)\(])\s*[\n\r]\s*[\n\r](\s*[\n\r])+/", "\n", $buffer);
////---------------------------------------------------------------------------------------------------------
//END Remove comments.    //START Remove all whitespaces    
$buffer = preg_replace('/(--\s+\>)/', 'HwRc', $buffer);  // protect space between: -- >
//-------------------------------------------------------- 
$buffer = preg_replace('/\s+/', ' ', $buffer);
$buffer = preg_replace('/\s*(?:(?=[=\-\+\|%&\*\)\[\]\{\};:\,\.\<\>\!\@\#\^`~]))/', '', $buffer);
$buffer = preg_replace('/(?:(?<=[=\-\+\|%&\*\)\[\]\{\};:\,\.\<\>\?\!\@\#\^`~]))\s*/', '', $buffer);
$buffer = preg_replace('/([^a-zA-Z0-9\s\-=+\|!@#$%^&*()`~\[\]{};:\'",<.>\/?])\s+([^a-zA-Z0-9\s\-=+\|!@#$%^&*()`~\[\]{};:\'",<.>\/?])/', '', $buffer);
//-------------------------------------------------------
$buffer = preg_replace('/(HwRc)/', '-- >', $buffer);  // Repair space between: -- >
//END Remove all whitespaces

j'ai juste pour le plaisir de tester cette ( var regex=/(ftp|https?):\/\//;alert('hello,world'); ) et ce /* foo(); // some comment */ et ceci: "Python's division: 1 // 2" et cet exemple //"you dope" et mon code de compression ceux qui n'endommagent pas l'exemple ci-dessus! COMMENTAIRE DU DESSUS:( Un analyseur stupide qui utilise des expressions régulières traitera le code JavaScript valide comme des commentaires! Donc peut-être que vous pouvez aussi écrire aucun parsers stupide avec regex???

je suis parti grossier pas un programmeur voulait juste que le plugin fonctionne comme je le voulais.... N'hésitez pas à laisser un commentaire si vous trouver un problème avec ce script avec des phrases javascript valides. Et de toute sorte de commentaires tags combiné (combinée ou non) qu'il ne résout pas correctement.. Parce que j'ai un grand handycap, Je n'ai plus de syntaxe Javascript. donc je ne sais pas à quoi m'attendre je l'ai juste testé sur des exemples que je pourrais trouver!

mis à jour ne doit plus Tester 8000.000 lignes fonctionne très bien maintenant.!

2
répondu John Smith 2016-01-23 00:14:02

j'ai frappé un scénario où je charge le code javascript sur le réseau via xhr, et besoin de nettoyer le code pour eval'ing. J'utilise ce code:

var cleanCode = function cleanCode(input) {
  // Remove special characters:
  return input.replace(/\/\/[^"'].*?\n/g, '') /* //comments, but ignore a "//" if there is a quote after it */
              .replace(/\n/g, '')             /* Leftover newlines */
              .replace(/\r/g, '');            /* Carriage returns  */
};

j'ai testé en utilisant ceci et le seul problème que j'ai eu était un commentaire comme:

//'key': 'value'

donc j'ai dû changer ce code pour le commentaire en ligne:

/*'key': 'value'*/ //LEAVE as inline comment, please

ce code ne sera pas modifié:

url += '//' + ...

n'hésitez pas à modifier/suggérer des modifications pour de la rendre plus lisible.

-1
répondu Devin G Rhode 2012-12-08 06:44:39

Motif pour supprimer les commentaires JS

$pattern = '/((?:\/\*(?:[^*]|(?:\*+[^*\/]))*\*+\/)|(?:\/\/.*))/';

Motif pour supprimer les commentaires en CSS

$pattern = '!/\*[^*]*\*+([^/][^*]*\*+)*/!'; 

$str = preg_replace($pattern, '', $str);

j'espère que ci-dessus devrait aider quelqu'un..

-1
répondu Dilip Rajkumar 2013-11-21 12:03:44