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

Link to comment
Share on other sites

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.

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.