...

View Full Version : Removing comments



Ultragames
08-02-2007, 02:56 AM
I need to have PHP read another file, and do two things (at least there are two that I don't know how to do.)

1) Delete anything after and including a // but only on that line. The line does not need to start with the // but if it exists, everything on the line after the // and including the // need to go.

2) Delete anything inbetween and including a /* and */ on any number of lines.

Basicly what I am doing is removing any comments from a JavaScript file. I am also replacing new lines and tabs with spaces, however I don't need help with that part of it.

Thank you for your help in figuring this one out.

FuZion
08-02-2007, 03:15 AM
I would use regex in the preg_replace function.

This regex should work: /\/\*(.+)\*\//
I'm not the best with this stuff so someone may have a better way.. I'm pretty sure that'll work though.. hope this helps!

Ultragames
08-02-2007, 04:28 AM
Your regex dosn't appear to do anything at all...


$var = <<<HEREDOC
var code = 'test'; // Remove me!
/*
Remove this too
*/
var code = 'test';
HEREDOC;

print_r( preg_replace('/\/\*(.+)\*\//', '', $var) );

Returns:


var code = 'test'; // Remove me!
/*
Remove this too
*/
var code = 'test';

And should return:


var code = 'test';
var code = 'test';

Did I miss a step?

s_pradeep
08-02-2007, 09:16 AM
You'll need to different regexes, one for single line comments and one for multi-line comments.


<?php
$var = <<<HEREDOC
var code = 'test'; // Remove me!
/*
Remove this too
*/
var code = 'test';
HEREDOC;

$var = preg_replace('!//.+!', '', $var);
$var = preg_replace('!/\*.+\*/!s', '', $var);

printf('<pre>%s</pre>',$var);
?>

s_pradeep
08-02-2007, 11:33 AM
A small fix here...



<?php
$var = <<<HEREDOC
var code = 'test'; // Remove me!
/*
Remove this too
*/

if(test) { callem();/* one more here */ return 1;} // test ok
/* hahahah */
var code = 'test';
HEREDOC;

//printf('<pre>%s</pre>',$var);

$var = preg_replace('!//.+!', '', $var);
$var = preg_replace('!/\*[^/\\*]+\*/!s', '', $var);

printf('<pre>%s</pre>',$var);
?>

Ultragames
08-03-2007, 12:01 AM
Thank you very much!



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum