Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
184 views
in Technique[技术] by (71.8m points)

javascript - How to remove JS comments using PHP?

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...