Jump to content

Remove JavaScript Comments


The Little Guy

Recommended Posts

I made a minifier (kinda), basically it removes newlines/tabs/2+ spaces in the html doc. What I would like to do is remove js comments in the html doc. BUT! I display php code on the page so I can not remove those comments.

 

so...

 

I would like to remove comments between the <script> and <style> tags, and ignore the ones between the <code> tags. Any suggestions on how to do this?

Link to comment
https://forums.phpfreaks.com/topic/263719-remove-javascript-comments/
Share on other sites

Is it me, or is this being greedy?

 

preg_match_all("/<script.+>.+<\/script>/isU", $template, $matches);
foreach($matches[0] as $match){
if(!empty($match)){
	echo "\n\n\n\n\n\n\n\n\n$match\n\n\n\n\n\n\n\n\n";
}
}

 

Output:

 

<script type="text/javascript" src="//jssnips.com/jquery/latest.js"></script><script type="text/javascript" src="//static1.phpsnips.com/js/anchorReader.js"></script>

 

I have about 5 - 10 places where script tags are located on a page, why is it pulling 2 script tags out as one match? They should each be their own match, and those two tags should have even matched.

Your .+ between the script tags in the regex requires that there be at least one character between the start and end tag for a match.  Since you have no characters between your start and end tags the match doesn't work on the individual pairs.  It matches both pairs as a whole because it counts the end/start tags as the required content in the middle.

 

Use .* for a zero or more match.

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.