PDA

View Full Version : Removing Comments from String



mail4kaja
01-12-2006, 11:33 AM
Hello......

I'm writing a PHP code that gives an JavaScript as output. That JavaScript takes two inputs. The results obtained from some manipulation using PHP is wrapped by these two strings. Then my site name is printed. Now my problem is I have to eliminate the comment start symbol (<!--) in the seond input string as this may cause my site name to be commented and NOT displayed. How can I find & eliminate an unpaired comment start symbol?

If any full comment is given in the string i.e., for example
String 1: Some text
String 2: Some text <!-- Some Comment --> <!-- Some Text

the Paired (Closed Comment) should not be eliminted only the last <!-- should be eliminated.

Please help me how to do this....

R. Kaja Mohideen
http://mymail.xmgfree.com/

12345c
01-12-2006, 03:58 PM
Insert "-->" то end, delete comments by regexp, then delete "-->" in the end if stay. :)

jscheuer1
01-12-2006, 08:22 PM
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd">
<html>
<head>
<title>Strip Open Comments - Demo</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script type="text/javascript">

var inString1="No Comments at all"
var inString2="<!-- not a comment <!-- this is a comment --> <!-- <!-- is comment --> <!-- not"
var inString3=" not a comment --> <!-- this is a comment --> not --> <!-- <!-- is comment --> <!-- not"

String.prototype.stripOpenComments = function(){
var str='', front=this.indexOf('<!--')<this.indexOf('-->')? 1 : 0, strA=this.split('<!--');
for (var i_tem = 0; i_tem < strA.length; i_tem++){
if ((front||i_tem)&&/-->/.test(strA[i_tem]))
strA[i_tem]='<!--'+strA[i_tem]
str+=strA[i_tem]
}
return str
}

</script>
</head>
<body>
<textarea rows="3" cols="93" id="text">
</textarea>
<script type="text/javascript">
document.getElementById('text').value=inString1.stripOpenComments()+'\n'+
inString2.stripOpenComments()+'\n'+
inString3.stripOpenComments()
</script>
</body>
</html>

jscheuer1
01-13-2006, 07:52 AM
I played around with this one a bit more and, if you want to strip orphan closing comment tags (-->'s with no leading <!--'s) as well, use this prototype function instead of the one on my demo page above:


String.prototype.stripOpenComments = function(){
if (this.indexOf('<!--')==-1)
return this.replace(/-->/g, '')
var str='', front=this.indexOf('<!--')<this.indexOf('-->')? 1 : 0, strA=this.split('<!--');
for (var i_tem = 0; i_tem < strA.length; i_tem++){
if ((front||i_tem)&&/-->/.test(strA[i_tem]))
strA[i_tem]='<!--'+strA[i_tem]
else
strA[i_tem]=strA[i_tem].replace(/-->/g, '')
while (/-->.*-->/.test(strA[i_tem]))
strA[i_tem]=strA[i_tem].replace(/-->(?!.*-->)/,'')
str+=strA[i_tem]
}
return str
}

mail4kaja
01-13-2006, 09:16 AM
Thanks. I got it working.

Thanks A Lot.

R. Kaja Mohideen
http://mymail.xmgfree.com