SPUG:escaping HTML

Brian Maher maherb at brimworks.com
Wed May 21 21:50:09 CDT 2003


If you want the text to display exactly as the string looks I would do 
this:

     my $string = "Foo & Bar >>\nYO!";
     my %translations =
         ("&" => "&",
          "<" => "&lt;",
          ">" => "&gt;",
          '"' => "&quot;",
          "'" => "&#39;",
          "\n" => "<br>\n");


     my $regex = "([" . join('', map { quotemeta($_) } keys 
%translations) . "])";
     $string =~ s/$regex/$translations{$1}/go;

     print $string;

This will guarantee your text will be displayed as is.  If this text 
will be displayed inside of a <textarea> or <pre> tag, then you won't 
want the "\n" to be translated.

On Sunday, May 11, 2003, at 07:06  PM, ced at carios2.ca.boeing.com wrote:

>
>> $ perl -ne 's/</&lt;/g; s/>/&gt;/g' < index.html > outdex.html
>           ^
>           ^
>           p
>
>
> With a couple more for safety:
>
> $ perl -pe 's/</&lt;/g;s/>/&gt;/g;s/"/&quot;/g;s/&/&amp;/g' \
>    < index.html > outdex.html
>
>
> --
> Charles DeRykus
> _____________________________________________________________
> Seattle Perl Users Group Mailing List
> POST TO: spug-list at mail.pm.org
> ACCOUNT CONFIG: http://mail.pm.org/mailman/listinfo/spug-list
> MEETINGS: 3rd Tuesdays, U-District, Seattle WA
> WEB PAGE: www.seattleperl.org
>
>




More information about the spug-list mailing list