Re: [PHP] [SOLVED] need some regex help to strip out // comments but not http:// urls

[email protected] (Sean Greenslade)
Newsgroups php.general
Message-ID <CA+100gCkq1YkrFcqMvriPjJT4Oe11GP3ZHjJnd15yq5ODw+ERA@mail.gmail.com>
On Wed, May 29, 2013 at 4:26 PM, Daevid Vincent <[email protected]> wrote:
>
>
>> -----Original Message-----
>> From: Sean Greenslade [mailto:[email protected]]
>> Sent: Wednesday, May 29, 2013 10:28 AM
>>
>> Also, (I haven't tested it, but) I don't think that example you gave
>> would work. Without any sort of quoting around the "http://"
>> , I would assume the JS interpreter would take that double slash as a
>> comment starter. Do tell me if I'm wrong, though.
>
> You're wrong Sean. :-p

Glad to hear it. I knew I shouldn't have opened my mouth. =P
(In all seriousness, I realize that I mis-read that code earlier. I
think I was still reeling from the suggestion of doing arbitrary
string replacements in files.)

>
> This regex works in all cases listed in my example target string.
>
> \s*(?<!:)//.*?$
>
> Or in my actual compress() method:
>
> $sBlob = preg_replace("@\s*(?<!:)//.*?$@m",'',$sBlob);
>
> Target test case with intentional traps:
>
> // another comment here
> <iframe src="http://foo.com">
> function bookmarksite(title,url){
>     if (window.sidebar) // firefox
>         window.sidebar.addPanel(title, url, "");
>     else if(window.opera && window.print){ // opera
>         var elem = document.createElement('a');
>         elem.setAttribute('href',url);
>         elem.setAttribute('title',title);
>         elem.setAttribute('rel','sidebar');
>         elem.click();
>     }
>     else if(document.all)// ie
>         window.external.AddFavorite(url, title);
> }
>

And if that's the only case you're concerned about, I suppose that
regex will do just fine. Just always keep an eye out for double
slashes elsewhere. My concern would be something within a quoted
string. If that happens, no regex will save you. As I mentioned
before, regexes aren't smart enough to understand whether they're
inside or outside matching quotes. Thus, a line like this may get
eaten by your regex:
document.getElementById("textField").innerHTML = "Lol slashes // are // fun";

The JS parser sees that the double slashes are inside a string, but
your regex won't. Just something to be aware of, especially because
it's something that might not show up right away.

-- 
--Zootboy

Sent from some sort of computing device.
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.