Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

How to remove JS comments using PHP? This question is updated: Nov. 4 2013 and answered by: Alexander Yancharuk But there is a problem right now. A new code: id = id.replace(///g,'');

This is my example:

<?php
$output = "
//remove comment
this1 //remove comment
this2 /* remove comment */
this3 /* remove
comment */
this4 /* * * remove
* * * *
comment * * */
this5 http://removecomment.com
id = id.replace(///g,''); //do not remove the regex //
";

$output = preg_replace( "/(?:(?:/*(?:[^*]|(?:*+[^*/]))**+/)|(?:(?<!:)//.*))/", "", $output ); //Yancharuk's code/regex
// "/(?<!:)//(.*)\n/ = my oldest code

echo nl2br($output);
?>

My Problems;

  1. Something wrong with the this1 line;
  2. The //comments is working but I can't create a codes to remove /* comment */ or by that comment with a line break

Here is the output, recent:



this1
this2
this3
this4
this5 http://removecomment.com
id = id.replace(/

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
180 views
Welcome To Ask or Share your Answers For Others

1 Answer

Try this:

$output = "
//remove comment
this1 //remove comment
this2 /* remove comment */
this3 /* remove
comment */
this4 /* * * remove
* * * *
comment * * */
this5 http://removecomment.com
id = id.replace(///g,''); //do not remove the regex //
HTTP+'//www.googleadservices.com/pagead/conversion'
";

$pattern = '/(?:(?:/*(?:[^*]|(?:*+[^*/]))**+/)|(?:(?<!:|\|')//.*))/';
$output = preg_replace($pattern, '', $output);

echo nl2br($output);

Result on codepad.org.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...