in reply to Removing html comments with regex
$comments =~ s/<!--.*?-->//g; $comments =~ s/<!--(.|\s)*?-->//g;
You, and several of the people replying, seem to have a wrong impression of what HTML comments are. HTML comments are not pieces of text delimited by <!-- and -->. It's more complicated. Zero or more comments may appear inside a comment declaration. The declaration is delimited by <! and >. Comments are delimited by --. There is optional whitescape after each comment.
The following quote is from RFC 1866, the only RFC to ever define an HTML standard:
To include comments in an HTML document, use a comment declaration. A comment declaration consists of `<!' followed by zero or more comments followed by `>'. Each comment starts with `--' and includes all text up to and including the next occurrence of `--'. In a comment declaration, white space is allowed after each comment, but not before the first comment. The entire comment declaration is ignored.NOTE - Some historical HTML implementations incorrectly consider any `>' character to be the termination of a comment.
For example:
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"> <HEAD> <TITLE>HTML Comment Example</TITLE> <!-- Id: html-sgml.sgm,v 1.5 1995/05/26 21:29:50 connolly Exp --> <!-- another -- -- comment --> <!> </HEAD> <BODY> <p> <!- not a comment, just regular old data characters ->
The SGML Handbook [1] has to say the following about comments:
10.3 Comment Declaration
A comment is a string of SGML characters that is used in the parameter separators of markup declarations to explain what the declaration is doing.It is also possible to have a declaration that contains nothing but comments; this is called a comment declaration. Comment declarations are frequently used in markup declaration subsets to separate the declarations from one another and to explain what each group of declarations is for. They can also be used by authors in the document instance to provide instructions for other people working with the document, or reminders for themselves.
[91] comment declaration = 2 mdo, [ <! ] ( comment, [ [92] 391: 7] 4 ( s | [ [5] 297:23] comment )* )?, [ [92] 391: 7] 6 mdc [ > ] [92] comment = 8 com, [ -- ] SGML character*, [ [50] 345: 1] 10 com [ -- ] No markup is recognized in a comment [ [92] 391:7], other than the 12 com delimiter that terminates it.
The s rule is similar to \s* in Perl regular expressions. The rule SGML character lists valid characters.
This means that a regexp to recognize HTML comments is something like:
/<!(?:--(?:[^-]*|-[^-]+)*--\s*)>/
Or you could simply do:
use Regexp::Common; /$RE{comment}{HTML}/
[1] Charles F. Goldfarb: The SGML Handbook. Oxford, Clarendon Press, 1990.
Abigail
|
|---|